jQueryAJAX没有得到PHP的响应
jQuery AJAX gets no response from PHP
当我尝试在PHP中发出jQueryAJAX请求时,我遇到了几个问题。我的简单例子有什么问题?
index.php
-加载JS、PHP并定义一个按钮和一个段落。
<html>
<head>
<script src='jquery-3.0.0.js'></script>
<script src='main.js'></script>
</head>
<body>
<button id="action" onClick="Send()">Send data</button>
<p id="result"></p>
<?php require('main.php'); ?>
</body>
</html>
main.js
-它包含与"onClick"事件关联的函数。
function Send(){
$.ajax({
url: 'main.php',
type: 'POST',
data: {
input: "test",
message: "Sending..."
},
contentType: 'application/json',
success: function(data) {
alert(data);
document.getElementById("result").innerHTML = "DONE!";
}
});
}
main.php-它监听POST请求,并发回一个JSON。
<?php
if ($_POST){
// Make a array with the values
$vals = [
'input' => $input,
'message' => $message
];
echo json_encode($vals);
}
success
回调运行,但alert
消息完全为空。CCD_ 5表示CCD_。
很明显,没有任何数据被发送回AJAX请求。我该怎么修?
这是因为您没有以JSON的形式从PHP发送响应。
在echo json_encode()
上方添加以下行;
header('Content-Type: application/json');
所以你的PHP代码看起来像这样,
<?php
if ($_POST){
// Make a array with the values
$vals = array(
'input' => $input,
'message' => $message
);
header('Content-Type: application/json');
echo json_encode($vals, JSON_PRETTY_PRINT); // Now we want to JSON encode these values to send them to $.ajax success.
exit; // to make sure you aren't getting nothing else
}
?>
同样正如@Ismail提到的dataType : 'json'
在.AJAX
调用中添加此内容以接受来自API的JSON响应。
在main_js.js 中
function Send(){
var data_JSON = {
input: "test",
message: "Sending..."
};
$.ajax({
url: 'main_php.php',
type: 'POST',
data: data_JSON,
dataType: 'json',
success: function(response){
if(response.type == "success")
{
alert(JSON.stringify(response.data));
alert(response.data.input);
document.getElementById("result").innerHTML = response.message;
}
else
{
document.getElementById("result").innerHTML = response.message;
}
}
});
}
在php代码中
<?php
$response= array();
if (isset($_POST) && !empty($_POST)){
// Make a array with the values
$vals = $_POST;
$response['data']=json_encode($vals); // Now we want to JSON
$response["type"]="success";
$response["message"]="Successfully posted";
}
else
{
$response=array(
"type"=>"error",
"message"=>"invalid post method"
);
}
ob_clean();
echo json_encode($response);
相关文章:
- 使用AJAX只获取PHP响应
- AJAX-没有得到简单的php响应(返回“undefined”)
- AJAX PHP - 响应是一个具有空值的对象
- 如果 PHP 响应等于某物,如何使 jQuery 警报
- DropzoneJS:上传成功后如何获得PHP响应
- PHP:响应 AJAX 发布请求
- 在javascript http post请求之后处理不同的php响应
- 使用 ajax 显示 php 响应文本
- PHP响应变得非常慢(使用MySQL)
- Ajax,处理 javascript 中的 php 响应
- 从 php 响应 AJAX 的更好方法
- jQuery认为每个PHP响应都有staus 0
- 将 PHP 响应输出为 XML
- 将PHP响应日期转换为客户端本地时间
- 使用jQuery将PHP响应的字符串分配给Javascript中的变量
- 如何在JavaScript中动态创建的输入字段中更新特定的输入字段,ajax从PHP响应
- 尝试用Javascript填充字段,由PHP响应
- 在HTML中使用返回的JSON编码AJAX PHP响应<作为值
- 如何在ajax中添加基于php响应的消息,同时处理
- 原型Javascript框架-获取PHP响应