我在表单的输入字段上有一个Ajax自动完成框。在jquery中,我具有以下ajax设置
$.ajax({
type: "POST",
url: myUrl,
data: $("#id__form").serialize(),
success: function(data){
alert("do something");
},
error: function (xhr, textStatus, thrownError) {
alert(xhr.status+ " "+ thrownError+ " " + textStatus);
},
dataType: "json"
});
在服务器端,我有以下php代码
$data = array('type' => 'error', 'message' => 'Error: '.$text);
header('HTTP/1.1 400 Bad Request');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode($data));
无论成功还是出错,一切都可以正常工作。但是,我没有弄清楚如何从jquery访问在php中定义为$ text的文本。
xhr.status为400,textStatus为“错误”,throwError为“错误请求”,但没有任何迹象表明我定义为$ text
我缺少什么?
最佳答案
如果您在文件中回显$ text变量,则可以从javascript文件中获取它。
php代码:
echo $text;
更改为javascript:
$.ajax({
type: "POST",
url: myUrl,
data: $("#id__form").serialize(),
success: function(data){
//do something with the data returned from php file
alert(data);//<---change to javascript code
},
error: function (xhr, textStatus, thrownError) {
alert(xhr.status+ " "+ thrownError+ " " + textStatus);
},
dataType: "json"
});
关于javascript - jQuery/PHP输出自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26941314/