jQuery $.ajax() 成功不会运行函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18882841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:41:51  来源:igfitidea点击:

$.ajax() success won't run function

javascriptajaxjquery

提问by JakeGIS

My question regards the $.ajax()jQuery method. I can't get the success parameter in $.ajax()to work.

我的问题是关于$.ajax()jQuery 方法的。我无法让成功参数$.ajax()起作用。

This works:

这有效:

$.ajax({
    type: 'POST',
    url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
    dataType: 'json',
    success: window.alert("inside aJax statement")

});

This does not:

这不会:

 $.ajax({
    type: 'POST',
    url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
    dataType: 'json',
    success: function(){
        window.alert("inside aJax statement");
    }                       
}); 

In the first case, I get a JavaScript alert window that lets me know the $.ajax()I called is working. All that is changed in the second block of code is I put the window.alert()inside a function() { window.alert(); }.

在第一种情况下,我会收到一个 JavaScript 警报窗口,让我知道$.ajax()我调用的对象正在工作。即在代码的第二块改变了这一切是我把window.alert()里面function() { window.alert(); }

The point of this is to verify that the $.ajax is running so I can put some actual useful code in the function(){}when the $.ajax runs successfully.

这样做的目的是验证 $.ajax 是否正在运行,以便我可以function(){}在 $.ajax 成功运行时放入一些实际有用的代码。

回答by Trevor

In your second example nothing will happen unless you get a successful call back from the server. Add an error callback as many here have suggested to see that indeed the ajax request is working but the server is not currently sending a valid response.

在您的第二个示例中,除非您从服务器成功回调,否则不会发生任何事情。添加一个错误回调,正如许多人建议的那样,以查看 ajax 请求确实在工作,但服务器当前没有发送有效的响应。

$.ajax({
        type: "POST",
        url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),                        
        dataType:"json",
        success: function(response){
                alert(response);        
      },
      error: function(jqXHR, textStatus, errorThrown){
          alert('error');
      }         
      });

helpful Linkin tracking down errors.

追踪错误的有用链接

回答by T.J. Crowder

Your first example does nothing whatsoever to prove that the ajaxcall has worked. All it does is prove that the ajaxfunction was reached, because the values of the properties in the anonymous object you're passing into the ajaxfunction are evaluated beforethe function is called.

你的第一个例子没有做任何事情来证明ajax调用有效。它所做的只是证明该ajax函数已到达,因为在调用该函数之前ajax会评估您传递给该函数的匿名对象中的属性值。

Your first example is basically the same as this:

您的第一个示例与此基本相同:

// THIS IS NOT A CORRECTION, IT'S AN ILLUSTRATION OF WHY THE FIRST EXAMPLE
// FROM THE OP IS WRONG
var alertResult = window.alert("inside aJax statement");
$.ajax({
    type: 'POST',
    url: "/getCodes.php?codes=billingCodes&parent=" + $('#wClient').val(),
    dataType: 'json',
    success: alertResult

})

E.g., firstthe alertis called and displayed, thenthe ajaxcall occurs with successreferencing the return value from alert(which is probably undefined).

例如,首先alert被调用并显示,然后ajax电话与发生success从引用的返回值alert(这可能是undefined)。

Your secondexample is correct. If you're not seeing the alert in your second example, it means that the ajaxcall is not completing successfully. Add an errorcallback to see why.

你的第二个例子是正确的。如果您在第二个示例中没有看到警报,则表示ajax呼叫未成功完成。添加error回调以查看原因。

回答by Alexandr Skachkov

In first case window.alert is executed immidiatly when you run $.ajax In second it run only when you receive answer from server, so I suspect that something wrong in you ajax request

在第一种情况下,window.alert 在您运行 $.ajax 时立即执行第二次它仅在您从服务器收到答案时运行,所以我怀疑您的 ajax 请求有问题

回答by Saram

I think that you do it right, but your request does not succeeds. Try add also error handler:

我认为你做对了,但你的请求没有成功。尝试添加错误处理程序:

error: function(){alert("Error");};

I guess that dataType does not match or something like that.

我猜 dataType 不匹配或类似的东西。

回答by SerhiyVas

It is 100% your second example is correct. Why it does nothing? Maybe because there is no success in the ajax call. Add "error" handler and check waht does your ajax call return with the browsers' developer tool -> Network -> XHR . This really helps in handling of broken / incorrect ajax requests

你的第二个例子是 100% 正确的。为什么它什么都不做?可能是因为ajax调用没有成功。添加“错误”处理程序并使用浏览器的开发人员工具 -> Network -> XHR 检查您的 ajax 调用是否返回。这确实有助于处理损坏/不正确的 ajax 请求

回答by Nathaniel Ford

You may want to try and use a promise:

您可能想尝试使用承诺:

var promise = $.ajax({
  type: 'POST',
  url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
  dataType: 'json'
});

promise.fail( function() {
  window.alert("Fail!");
});

promise.done( function() {
  window.alert("Success!");
});

What this does is saves the ajaxcall to a variable, and then assigns additional functionality for each of the return states. Make sure that the data type you are returning is actually json, though, or you may see strange behavior!

这样做是保存对ajax变量的调用,然后为每个返回状态分配附加功能。但是,请确保您返回的数据类型实际上是 json,否则您可能会看到奇怪的行为!

Note that js is single-threaded; the reason your first example works is because it actually executes the code next 'success' and stores the result. In this case there is nothing to store; it just pops an alert window. That means that the ajax call is leaving the client after the alert is fired: use the developer tools on Chrome or equivalent to see this.

注意js是单线程的;您的第一个示例有效的原因是它实际上执行了下一个“成功”的代码并存储了结果。在这种情况下,没有什么可存储的;它只是弹出一个警告窗口。这意味着在触发警报后 ajax 调用将离开客户端:使用 Chrome 上的开发人员工具或等效工具来查看这一点。

By putting a function there, you assign it to do something when the ajax call returns much later in the thread (or, more precisely, in a new thread started when the response comes back).

通过在那里放置一个函数,当 ajax 调用在线程中稍后返回时(或者,更准确地说,在响应返回时启动的新线程中),您可以指定它执行某些操作。