Javascript 发送JSON数据的AJAX调用
我正在开发一个聊天系统,它使用AJAX自动刷新。首先,我使用jQuery$.post函数,但是因为我想从PHP脚本返回JSON数据,所以我想使用$.ajax函数。我的脚本使用$.post函数运行良好,但无法返回JSON。以下是相关代码: Javascript:Javascript 发送JSON数据的AJAX调用,javascript,php,jquery,json,ajax,Javascript,Php,Jquery,Json,Ajax,我正在开发一个聊天系统,它使用AJAX自动刷新。首先,我使用jQuery$.post函数,但是因为我想从PHP脚本返回JSON数据,所以我想使用$.ajax函数。我的脚本使用$.post函数运行良好,但无法返回JSON。以下是相关代码: Javascript: $.ajax({ url: "pages/loadmessage.php", type: "POST", data: {"c": getUrlParameter("c"), "t": messagetime},
$.ajax({
url: "pages/loadmessage.php",
type: "POST",
data: {"c": getUrlParameter("c"), "t": messagetime},
dataType: "json",
success: function(pData){
console.log(pData);
},
error: function(xhr, status, error) {
alert(error + status);
}
});
PHP代码:
<?php
require_once("../init.php");
header('Content-Type: application/json');
if (Input::exists() && Input::get("c") && Input::get("t")) {
$chat = new Chat($user->data()->ID, Input::get("c"));
$messages = $chat->getNewMessages(Input::get("t"), $user->data()->ID);
if ($messages) {
$result = array(
'topic' => $chat->getTopic(),
'messages' => array()
);
foreach($messages as $m) {
array_push($result['messages'], array('source' => 'mine', 'Text' => $m->Text));
}
echo json_encode("string!!!");
}
} else {
echo json_encode("string" . Input::get("c") . Input::get("t") . Input::exists());
}
?>
我已经尝试将AJAX调用的contentType设置为“application/json”,并使用json.stringify将数据转换为json,但是没有输入数据进入PHP脚本。如果只向PHP脚本发送一个参数(数据:{“c”:getUrlParameter(“c”)}),那么代码就可以运行了。。。
我已经搜索了StackOverflow,但找不到解决方案
谢谢你,例如:
Index.html
<script type="text/javascript">
$.ajax({
url: "out.php",
type: "POST",
data: {"param1": "test 1", "param2": "test2"},
dataType: "json",
success: function(data){
alert("param1:"+data.param1+" | param2:"+data.param2);
},
error: function(xhr, status, error) {
alert(error + status);
}
});
</script>
$.ajax({
url:“out.php”,
类型:“POST”,
数据:{“param1”:“test1”,“param2”:“test2”},
数据类型:“json”,
成功:功能(数据){
警报(“param1:+data.param1+”| param2:+data.param2);
},
错误:函数(xhr、状态、错误){
警报(错误+状态);
}
});
out.php
<?php
if(isset($_POST["param1"])){ $param1 = $_POST["param1"];}
if(isset($_POST["param2"])){ $param2 = $_POST["param2"];}
$out = array("param1"=>$param1,"param2"=>$param2);
echo(json_encode($out));
?>
您是否检查了的最后一个参数?console中的任何错误消息$.post
可以返回JSON,您只需使用正确的语法:$.post(“pages/loadmessage.php”,“c”:getUrlParameter(“c”),“t”:messagetime},function(pData){/*do stuff*/},“JSON”)代码>$.post只是.ajax的包装器。jsonYou说“使用JSON.stringify,但是没有输入数据进入PHP脚本”,如果是这种情况,您应该使用它在服务器端捕获JSON字符串$rawData=文件获取内容(“php://input"); // 如果json返回json_decode($rawData)无效,则返回null;