简体   繁体   English

ajax-将数据作为json发送到php服务器并接收响应

[英]ajax - sending data as json to php server and receiving response

I'm trying to grasp more than I should at once. 我试图一次掌握更多。

Let's say I have 2 inputs and a button, and on button click I want to create a json containing the data from those inputs and send it to the server. 假设我有2个输入和一个按钮,然后单击按钮,我想创建一个包含来自这些输入的数据的json并将其发送到服务器。

I think this should do it, but I might be wrong as I've seen a lot of different (poorly explained) methods of doing something similar. 我认为应该这样做,但是我可能错了,因为我已经看到很多不同的(做得不好解释)类似的方法。

    var Item = function(First, Second) {
        return {
            FirstPart : First.val(), 
            SecondPart : Second.val(), 
        };
    };

    $(document).ready(function(){
        $("#send_item").click(function() {
            var form = $("#add_item");

            if (form) {
                item = Item($("#first"), $("#second"));

                $.ajax ({
                    type: "POST",
                    url: "post.php", 
                    data: { 'test' : item },
                    success: function(result) {
                        console.log(result);
                    }
                });
            }
        });
    });

In PHP I have 在PHP中我有

class ClientData
{
    public $First;
    public $Second;

    public function __construct($F, $S)
    {
        $this->First = F;
        $this->Second = S;
    }
}

if (isset($_POST['test']))
{
    // do stuff, get an object of type ClientData
}

The problem is that $_POST['test'] appears to be an array (if I pass it to json_decode I get an error that says it is an array and if I iterate it using foreach I get the values that I expect to see). 问题是$ _POST ['test']似乎是一个数组(如果我将其传递给json_decode,则会收到一个错误消息,指出它是一个数组,如果我使用foreach对其进行迭代,则会得到我期望看到的值) 。 Is that ajax call correct? 那ajax电话正确吗? Is there something else I should do in the PHP bit? 在PHP中还有什么我应该做的吗?

You should specify a content type of json and use JSON.stringify() to format the data payload. 您应将内容类型指定为json,并使用JSON.stringify()格式化数据有效负载。

$.ajax ({
   type: "POST",
   url: "post.php", 
   data: JSON.stringify({ test: item }),
   contentType: "application/json; charset=utf-8",
   success: function(result) {
      console.log(result);
   }
});

When sending an AJAX request you need to send valid JSON. 发送AJAX请求时,您需要发送有效的JSON。 You can send an array, but you need form valid JSON before you send your data to the server. 您可以发送一个数组,但是在将数据发送到服务器之前,您需要表单有效的JSON。 So in your JavaScript code form valid JSON and send that data to your endpoint. 因此,以您的JavaScript代码形式使用有效的JSON并将该数据发送到您的端点。

In your case the test key holds a value containing a JavaScript object with two attributes. 在您的情况下, test键包含一个value ,该value包含具有两个属性的JavaScript对象。 JSON is key value coding in string format, your PHP script does not not how to handle JavaScript (jQuery) objects. JSON是字符串格式的键值编码,您的PHP脚本没有如何处理JavaScript(jQuery)对象。

https://jsfiddle.net/s1hkkws1/15/ https://jsfiddle.net/s1hkkws1/15/

This should help out. 这应该有所帮助。

For sending raw form data: 发送原始form数据:
js part: js部分:

$.ajax ({
    type: "POST",
    url: "post.php", 
    data: item ,
    success: function(result) {
        console.log(result);
    }
});

php part: php部分:

..
if (isset($_POST['FirstPart']) && isset($_POST['SecondPart']))
{
    $fpart = $_POST['FirstPart'];
    $spart = $_POST['SecondPart'];
    $obj = new ClientData($fpart, $spart);
}
...

For sending json string: 发送json字符串:
js part: js部分:

$.ajax ({
    type: "POST",
    url: "post.php", 
    data: {'test': JSON.stringify(item)},
    success: function(result) {
        console.log(result);
    }
});

php part: php部分:

..

if (isset($_POST['test']))
{
    $json_data = $_POST['test'];
    $json_arr = json_decode($json_data, true);
    $fpart = $json_arr['FirstPart'];
    $spart = $json_arr['SecondPart'];
    $obj = new ClientData($fpart, $spart);
}
...

Try send in ajax: 尝试发送ajax:

data: { 'test': JSON.stringify(item) },

instead: 代替:

data: { 'test' : item },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM