简体   繁体   English

在ajax发布中发送json字符串

[英]Send json string in ajax post

var myData = JSON.stringify($('form').serializeArray());

$.ajax({ 
    cache: false,
    url: "http://localhost/Demo/store.php",
    type: "POST",
    data: myData,           
    complete: function (xhr, status) {
        if (status === 'error' || !xhr.responseText) {
            alert(status);              
        }
        else {
            var r = xhr.responseText;                       
        }
    }
});

$decoded = json_decode($_REQUEST['myData'],true);
print_r($_REQUEST);
exit;

if (is_array($decoded))
{
    foreach ($decoded as $value) {
        echo $value["name"] . "=" . $value["value"];
    }
}

When i am trying to decode the data in php the error is undefined index myData..Please help me..Thanks. 当我尝试解码php中的数据时,错误是未定义的索引myData ..请帮助我..谢谢。

试试看:

$decoded = json_decode($_POST['myData'],true);

Try this when call ajax 调用ajax时尝试一下

data: {'myData' : myData},

Then access using 然后使用

json_decode($_POST['myData'],true); 

or 要么

json_decode($_REQUEST['myData'],true);

try this pass datatype : 试试这个传递数据类型:

$.ajax({
    url: 'http://localhost/Demo/store.php',
    type: 'POST',
    dataType: 'json',
    data: $('#form').serialize(),
    success: function(xhr, status) {
    if (status === 'error' || !xhr.responseText) {
        alert(status);              
    }
    else {
        var r = xhr.responseText;                       
    }
}
});

When you pass a string as the data property is just appends it as a parameter query string to the URL. 当您将字符串作为data属性传递时,只是将其作为参数查询字符串附加到URL。 If you want to send an encoded JSON string you still need to give it a name: 如果要发送编码的JSON字符串,则仍需要为其命名:

data: {myData: myData}

Now you can use the myData request parameter in your PHP script. 现在,您可以在PHP脚本中使用myData请求参数。

used dataType:json; 使用的dataType:json; tosend json. 发送json。

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

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