doushan5222 2016-02-20 14:12
浏览 70

too long

Is it possible to send JSON data from the client side using ajax (with jQuery), to a PHP page and use json_decode with all the variables exactly the same data type? I thought JSON was suppose to preserve this but it seems it doesn't work if you send it to PHP. If it doesn't do this then I'm not sure why I should ever be using JSON. I might as well just use a standard POST request.

My problem is that I need to send data to PHP for it to be inserted into MySQL which requires the right variable types being inserted, but when the data arrives from JSON it is all converted to a string. I think I'm misunderstanding what JSON is suppose to be used for. Most likely, and if so can anyone explain this to me?

Does this mean I need to manually convert everything on the PHP side all the time throughout my entire web application? That would be a real pain.

// JavaScript:

$.ajax({
    type: "POST",
    url: "program.php",

    data: {
        posting: true,
        json: JSON.stringify({
            posting: true,
            id: 6,  // should remain an integer
        })
    },

    success: function(data) {
        console.log(data);
    }
});


// PHP:

if (array_key_exists("posting", $_POST)) {
    $result = json_decode($_POST["json"]);
    echo gettype($result->id); // string (all values in $result are strings still)
    exit();
}

EDIT: The reason I'm worried about variable types is because I am trying to use prepared statements with MySQL and the bind_param function requires you to enter the variable types. This is a PHP function I created to handle this for me:

public static function insert($query, $params) {        
    $statement = mysqli_prepare(self::$connection, $query);
    foreach ($params as $value) {
        switch (gettype($value)) {
            case "boolean":
                $value = (int) $value;
            case "integer":
                $statement->bind_param("i", $value);
                break;
            case "double":
                $statement->bind_param("d", $value);
                break;
            case "string":
                // it is ALWAYS a string even though some as suppose to be integers
                $statement->bind_param("s", $value);
                break;
            default: 
                echo "error type: " . gettype($value);
                return;
        }
    }

    $statement->execute();
    $statement->fetch();
    $result = $statement->get_result();
    $statement->close();
    return $result;
}
  • 写回答

2条回答 默认 最新

  • dongzhashou0116 2016-02-20 14:21
    关注

    If you're still getting stuck with this I have done a basic example that covers the HTML/JavaScript using Jquery and the PHP page (logging data to a text file)

    JavaScript Code - Index.html

    <a href="#" class="button">Submit</a>
    
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script>
    
        $(".button").on("click", function(){
            ajaxSubmit();
        });
    
        var ajaxSubmit = function(){
    
            var obj = {};
    
            obj['foo'] = {};
            obj['foo']['type'] = 'integer';
            obj['foo']['value'] = 1;
    
            obj['bar'] = {};
            obj['bar']['type'] = 'string';
            obj['bar']['value'] = 'hello';
    
            sendData = JSON.stringify(obj);
    
            $.ajax({
                type: "POST",
                url: "program.php",
                data: {'json': sendData},
    
                success: function(data) {
                    console.log(data);
                }
            });
    
        };
    
    </script>
    

    PHP Code - program.php

    <?php
    
        $data = $_REQUEST;
    
        $obj = json_decode($data['json']);
    
        foreach ($obj as $var) {
    
            switch ($var->type) {
                case 'integer':
                    fileWrite('Integer: '.$var->value);
                    break;
                case 'string':
                    fileWrite('String: '.$var->value);
                    break;
            }
    
        }
    
        function fileWrite ($string) {
    
            if (is_array($string)){
                $string = 'Array: '.print_r($string, true);
            }
    
            if(is_object($string)) {
                $string = 'Object: '.print_r($string, true);
    
            }
    
            $fp = fopen('output.txt', 'a');
            fwrite($fp, $string."
    ");
            fclose($fp);
    
        }
    
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值