我有一个ajax调用在MVC视图调用一个函数调用其他5个函数之前完成。每个函数都有一个if/else,用于在失败时返回自己的错误消息,并显示需要重新加载原始页面的错误消息。但是如果没有错误,ajax调用应该更新为完整的页面。我知道成功函数中一个简单的if/else语句将完成此操作,并且我在每个函数的失败中放置了相同的简单错误变量。但是我不能将变量从成功函数响应中拉出以在成功函数if/else语句中使用。我的ajax调用在下面,我在服务器端运行PHP。
function sendstuff(data) {
$.ajax({
type:"POST",
datatype:'json',
cache: false,
data: data,
url:"/Orders/getitem/",
success:function(resp, status, jxr){
alert(resp);
if(resp.fail == "error") {
// error handling, show data.message or what you want.
location.reload(true);
} else {
// same as above but with success
$('body').html(resp);
}
});
return false;
};
下面是错误从
发送的地方if ( $status != 201 ) {
// $this->Flash->error(__('There was an error with the entry. Please, try again.'));
$ajaxerr['fail'] = 'error';
echo json_encode($ajaxerr);
die("Error: call to URL $url failed with status $status, response $result, curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch));
,这就是响应中的内容,因为它每次都加载成功函数的else部分。
{"fail":"error"}Error: call to URL https://api.blank failed with status 400, response {"name":"VALIDATION_ERROR","details":[{"field":"blank.fng_ints[0].ct_issue","issue":"date cannot be in the past."}],"message":"Invalid request. See details.","information_link":"https://developer.api/#VALIDATION_ERROR","debug_id":"24f4"}, curl_error , curl_errno 0
我可以看到它正在传递var,但我不能把它拉出来用于成功函数if/else语句。任何帮助都是感激的。
您的服务器响应不是有效的JSON响应,因此无法正确解析,因此无法获得成功消息
将服务器更改为
if ( $status != 201 ) {
// $this->Flash->error(__('There was an error with the entry. Please, try again.'));
$ajaxerr['fail'] = 'error';
$ajaxerr['msg'] = "Error: call to URL $url failed with status $status, response $result, curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch);
echo json_encode($ajaxerr);
exit;
}
然后解析为
{
"fail":"error",
"msg":"..."
}
无论如何,如果你有一个服务器错误,你最好从服务器发送一个真正的错误消息(使用HTTP状态>= 400),然后在jQuery中捕获它的error
回调,而不是success
回调
$.ajax( {
...
success: function() {
//handle success request
},
error: function() {
//handle failed requests
}
})
die();
调用在json结构之外的响应中放置字符串输出,这会导致Ajax函数无法解析响应。
考虑这样做:
$ajaxerr['fail'] = 'error';
$ajaxerr['reason'] = "Error: call to URL $url failed with status $status, response $result, curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch);
echo json_encode($ajaxerr);
die();
在你的代码中,你的响应不是json对象,因为'死亡'调用也会产生输出。所以不带任何参数调用die();
我解决了这个问题。我所要做的就是将resp设置为变量,并删除了所有不必要的东西,我觉得自己像个白痴,浪费了我的生命,但它是固定的。谢谢大家,特别是Yaron U.