2014-10-16 90 views
0

这是一个很琐碎的问题,更多的是好奇..返回成功或失败的jQuery AJAX标准要求

你们如何返回上一个jQuery Ajax的数据呼叫? “成功”还是“失败”,0或1,还有其他什么?

有没有更好的方法来做到这一点?最佳做法是什么?

public function ajaxCheckTask(){ 

    $task = Task::findOrFail(Input::get('id')); 

    if($task->user_id == Auth::user()->id){ 
     $task->mark(); 
     return 'success'; 
    } 

    return 'fail'; 

} 

回答

0

AJAX表示**Asynchronous** JavaScript and XML。所以你不能返回成功或失败,因为请求会是你正在做的异步操作,但是你可以对成功或失败做出一个动作。我已在JavaScript中的代码示例(来源:W3Schools的情况下,如果你想知道更多)

JAVASCRIPT

xmlhttp=new XMLHttpRequest(); 
xmlhttp.onreadystatechange=function(){ 
    if (xmlhttp.readyState==4 && xmlhttp.status==200){ 
     // Do the success action 
    } 
    else{ 
     // Do the failure action 
    } 
} 
xmlhttp.open("GET OR POST","URL TO CALL"); 
xmlhttp.send("DATA TO SEND"); 

JQUERY

$.ajax({ 
    url: URL, // URL to post the data 
    method: 'post',// suitable http verb 
    data: '', // values to be passed with the request 
    success: function(response) { 
     // Do the success action 
    }, 
    failure : function(response){ 
     // Do the failure action 
    } 
}); 
+0

请提供详细代码的有用答案。如果您使用任何其他jQuery AJAX方法(例如$ .get,$ .getJSON等),则必须将其更改为$ .ajax(因为您只能将配置参数传递给$ .ajax)并提供变量状态async:假; – 2014-10-17 07:24:52

+0

我已经解决了OP真正要求的是“是否可以在ajax调用上返回成功或失败”。答案是否定的。如果你正在谈论同步请求,那么它被称为SJAX而不是AJAX。我写的代码是让OP更好地理解答案。 – 2014-10-17 07:32:24

0

你这是怎么调用来自后端的成功消息。

$.ajax({ 
    url: URL, 
    method: 'post', 
    dataType: 'json', 
    data: {"var":"val"} 
    success: function(response) { 
     alert(response); 
    }, 
    failure : function(response){ 
     alert(response); 
    } 

});