Javascript Ajax 成功事件不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1969476/
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-22 22:10:26  来源:igfitidea点击:

Ajax success event not working

javascriptjqueryajax

提问by codingbbq

I have a registration form and am using $.ajaxto submit it.

我有一个注册表并正在使用$.ajax它来提交。

This is my AJAX request:

这是我的 AJAX 请求:

$(document).ready(function() {
    $("form#regist").submit(function() {
        var str = $("#regist").serialize();
        $.ajax({
            type: 'POST',
            url: 'submit1.php',
            data: $("#regist").serialize(),
            dataType: 'json',
            success: function() {
                $("#loading").append("<h2>you are here</h2>");
            }        
        });
        return false;        
    });
});

In my submit1.phpfile I check for the existence of fields email addressand usernamein the database. I wish to display an error message if those value exist without a page refresh.

在我的submit1.php文件中,我检查数据库中是否存在字段电子邮件地址用户名。如果这些值在没有页面刷新的情况下存在,我希望显示一条错误消息。

How can I add this to the successcallback of my AJAX request?

如何将其添加到我的 AJAX 请求的成功回调中?

回答by Tatu Ulmanen

The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with error:callback function.

结果可能不是 JSON 格式,因此当 jQuery 尝试解析它时,它失败了。您可以使用error:回调函数捕获错误。

You don't seem to need JSON in that function anyways, so you can also take out the dataType: 'json'row.

无论如何,您似乎不需要该函数中的 JSON,因此您也可以取出该dataType: 'json'行。

回答by js newbee

Although the problem is already solved i add this in the hope it will help others.

虽然问题已经解决了,我还是加了这个,希望能帮到其他人。

I made the mistake an tried to use a function directly like this (success: OnSuccess(productID)). But you have to pass an anonymous function first:

我犯了一个错误,试图直接使用这样的函数(成功:OnSuccess(productID))。但是你必须先传递一个匿名函数:

  function callWebService(cartObject) {

    $.ajax({
      type: "POST",
      url: "http://localhost/AspNetWebService.asmx/YourMethodName",
      data: cartObject,
      contentType: "application/x-www-form-urlencoded",
      dataType: "html",
      success: function () {
        OnSuccess(cartObject.productID)
      },
      error: function () {
        OnError(cartObject.productID)
      },
      complete: function () {
        // Handle the complete event
        alert("ajax completed " + cartObject.productID);
      }
    });  // end Ajax        
    return false;
  }

If you do not use an anonymous function as a wrapper OnSuccess is called even if the webservice returns an exception.

如果您不使用匿名函数作为包装器,即使 Web 服务返回异常,也会调用 OnSuccess。

回答by Allen

I tried removing the dataType row and it didn't work for me. I got around the issue by using "complete" instead of "success" as the callback. The success callback still fails in IE, but since my script runs and completes anyway that's all I care about.

我尝试删除 dataType 行,但它对我不起作用。我通过使用“完成”而不是“成功”作为回调来解决这个问题。成功回调在 IE 中仍然失败,但由于我的脚本运行并完成,这就是我所关心的。

$.ajax({
    type: 'POST',
    url: 'somescript.php',
    data: someData,
    complete: function(jqXHR) {
       if(jqXHR.readyState === 4) {
          ... run some code ... 
       }   
    }        
 });

in jQuery 1.5 you can also do it like this.

在 jQuery 1.5 中,您也可以这样做。

var ajax = $.ajax({
    type: 'POST',
    url: 'somescript.php',
    data: 'someData'
});
ajax.complete(function(jqXHR){
    if(jqXHR.readyState === 4) {
        ... run some code ... 
    }
});

回答by Delfin

Make sure you're not printing (echo or print) any text/data prior to generate your JSON formated data in your PHP file. That could explain that you get a -sucessfull 200 OK- but your sucess event still fails in your javascript. You can verify what your script is receiving by checking the section "Network - Answer" in firebug for the POST submit1.php.

在 PHP 文件中生成 JSON 格式的数据之前,请确保您没有打印(回显或打印)任何文本/数据。这可以解释您得到 -sucessfull 200 OK- 但您的成功事件在您的 javascript 中仍然失败。您可以通过检查萤火虫中 POST submit1.php 的“网络 - 答案”部分来验证您的脚本正在接收什么。

回答by dxh

Put an alert()in your successcallback to make sure it's being called at all.

alert()在您的success回调中放入一个以确保它被完全调用。

If it's not, that's simply because the request wasn't successful at all, even though you manage to hit the server. Reasonable causes could be that a timeout expires, or something in your php code throws an exception.

如果不是,那只是因为请求根本没有成功,即使您设法访问了服务器。合理的原因可能是超时到期,或者您的 php 代码中的某些内容引发了异常。

Install the firebug addon for firefox, if you haven't already, and inspect the AJAX callback. You'll be able to see the response, and whether or not it receives a successful (200 OK) response. You can also put another alert()in the completecallback, which should definitely be invoked.

如果您还没有安装 firefox 的 firebug 插件,请检查 AJAX 回调。您将能够看到响应,以及它是否收到成功的 (200 OK) 响应。您还可以alert()complete回调中放置另一个,它绝对应该被调用。

回答by Thusitha Wickramasinghe

I had same problem. it happen because javascriptexpect jsondata type in returning data. but if you use echo or print in your php this situation occur. if you use echofunction in phpto return data, Simply remove dataType : "json"working pretty well.

我有同样的问题。它发生是因为javascript期望json返回数据中的数据类型。但是如果您在 php 中使用 echo 或 print 会发生这种情况。如果您使用echo函数 inphp返回数据,只需删除dataType : "json"工作得很好。

回答by sarink

I was returning valid JSON, getting a response of 200 in my "complete" callback, and could see it in the chrome network console... BUT I hadn't specified

我正在返回有效的 JSON,在我的“完整”回调中得到 200 的响应,并且可以在 chrome 网络控制台中看到它......但我没有指定

dataType: "json"

once I did, unlike the "accepted answer", that actually fixed the problem.

一旦我这样做了,与“接受的答案”不同,实际上解决了问题。

回答by thowa

I'm using XML to carry the result back from the php on the server to the webpage and I have had the same behaviour.

我正在使用 XML 将结果从服务器上的 php 传回网页,并且我有相同的行为。

In my case the reason was , that the closing tag did not match the opening tag.

就我而言,原因是,结束标签与开始标签不匹配。

<?php
....
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>
    <result>
        <status>$status</status>
        <OPENING_TAG>$message</CLOSING_TAG>
    </result>";
?>

回答by Andresa Martins

I had this problem using an ajax function to recover the user password from Magento. The success event was not being fired, then I realized there were two errors:

我使用 ajax 函数从 Magento 恢复用户密码时遇到了这个问题。成功事件没有被触发,然后我意识到有两个错误:

  1. The result was not being returned in JSON format
  2. I was trying to convert an array to JSON format, but this array had non-utf characters
  1. 结果未以 JSON 格式返回
  2. 我试图将数组转换为 JSON 格式,但该数组具有非 utf 字符

So every time I tried to use json_eoncde() to encode the returning array, the function was not working because one of its indexes had non-utf characters, most of them accentuation in brazilian portuguese words.

因此,每次我尝试使用 json_eoncde() 对返回的数组进行编码时,该函数都无法正常工作,因为其索引之一具有非 utf 字符,其中大多数是巴西葡萄牙语单词的重音。

回答by user7285134

I tried to return string from controller but why control returning to error block not in success of ajax

我试图从控制器返回字符串,但为什么控制返回到错误块的 ajax 没有成功

var sownum="aa";
$.ajax({
    type : "POST",
    contentType : 'application/json; charset=utf-8',
    dataType : "JSON",
    url : 'updateSowDetails.html?sownum=' + sownum,
    success : function() {
        alert("Wrong username");
    },
    error : function(request, status, error) {

        var val = request.responseText;
        alert("error"+val);
    }
});