简体   繁体   English

Ajax 成功事件不起作用

[英]Ajax success event not working

I have a registration form and am using $.ajax to 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.php file I check for the existence of fields email address and username in the database.在我的submit1.php文件中,我检查数据库中是否存在字段电子邮件地址用户名 I wish to display an error message if those value exist without a page refresh .如果这些值在没有页面刷新的情况下存在,我希望显示一条错误消息。

How can I add this to the success callback of my AJAX request?如何将其添加到我的 AJAX 请求的成功回调中?

The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails.结果可能不是 JSON 格式,因此当 jQuery 尝试解析它时,它失败了。 You can catch the error with error: callback function.您可以使用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'行。

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)).我犯了一个错误,试图直接使用这样的函数(成功:OnSuccess(productID))。 But you have to pass an anonymous function first:但是你必须先传递一个匿名函数:

  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。

I tried removing the dataType row and it didn't work for me.我尝试删除 dataType 行,但它对我不起作用。 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.成功回调在 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 ... 
    }
});

Make sure you're not printing (echo or print) any text/data prior to generate your JSON formated data in your PHP file.在 PHP 文件中生成 JSON 格式的数据之前,请确保您没有打印(回显或打印)任何文本/数据。 That could explain that you get a -sucessfull 200 OK- but your sucess event still fails in your javascript.这可以解释您得到 -sucessfull 200 OK- 但您的成功事件在您的 javascript 中仍然失败。 You can verify what your script is receiving by checking the section "Network - Answer" in firebug for the POST submit1.php.您可以通过检查萤火虫中 POST submit1.php 的“网络 - 答案”部分来验证您的脚本正在接收什么。

Put an alert() in your success callback to make sure it's being called at all.在您的success回调中放置一个alert()以确保它被完全调用。

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.如果您还没有安装 firefox 的 firebug 插件,请检查 AJAX 回调。 You'll be able to see the response, and whether or not it receives a successful (200 OK) response.您将能够看到响应,以及它是否收到成功的 (200 OK) 响应。 You can also put another alert() in the complete callback, which should definitely be invoked.您还可以在complete回调中放置另一个alert() ,它绝对应该被调用。

I had same problem.我有同样的问题。 it happen because javascript expect json data type in returning data.发生这种情况是因为javascript期望在返回数据时使用json数据类型。 but if you use echo or print in your php this situation occur.但是如果您在 php 中使用 echo 或 print 会发生这种情况。 if you use echo function in php to return data, Simply remove dataType : "json" working pretty well.如果您在php使用echo函数返回数据,只需删除dataType : "json"工作得很好。

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.一旦我这样做了,与“接受的答案”不同,实际上解决了问题。

You must declare both Success AND Error callback.您必须同时声明成功和错误回调。 Adding添加

error: function(err) {...} 

should fix the problem应该解决问题

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>";
?>

I had this problem using an ajax function to recover the user password from Magento.我使用 ajax 函数从 Magento 恢复用户密码时遇到了这个问题。 The success event was not being fired, then I realized there were two errors:成功事件没有被触发,然后我意识到有两个错误:

  1. The result was not being returned in JSON format结果未以 JSON 格式返回
  2. I was trying to convert an array to JSON format, but this array had non-utf characters我试图将数组转换为 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 字符,其中大多数是巴西葡萄牙语单词的重音。

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);
    }
});

I faced the same problem when querying controller which does not return success response, when modified my controller to return success message problem was solved.我在查询不返回成功响应的控制器时遇到了同样的问题,当修改我的控制器以返回成功消息时问题得到解决。 note using Lavalite framework.注意使用 Lavalite 框架。 before:之前:

public function Activity($id)
    {
        $data=getData();
        return
            $this->response->title('title')
                ->layout('layout')
                ->data(compact('data'))
                ->view('view')
                ->output();
    }
after code looks like:
    try {
            $attributes = $request->all();
            //do something
            return $this->response->message('')
                ->code(204)
                ->status('success')
                ->url('url'. $data->id)
                ->redirect();
        } catch (Exception $e) {
            return $this->response->message($e->getMessage())
                ->code(400)
                ->status('error')
                ->url('nothing Wrong')
                ->redirect()
        }

this worked for me这对我有用

I had the same problem i solved it in that way: My ajax:我遇到了同样的问题,我以这种方式解决了它:我的 ajax:

event.preventDefault();
$.ajax('file.php', {
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({tab}), 
success: function(php_response){
            if (php_response == 'item') 
                {
                    console.log('it works');
                }
            }
        })

Ok.好的。 The problem is not with json but only php response.问题不在于 json,而在于 php 响应。 Before: my php response was:之前:我的 php 响应是:

echo 'item';

Now:现在:

$variable = 'item';
 echo json.encode($variable);

Now my success working.现在我的成功工作。 PS.附注。 Sorry if something is wrong but it is my first comment on this forum :)对不起,如果有什么问题,但这是我在这个论坛上的第一条评论:)

在我的情况下,错误是在服务器端,因此它返回一个 html

wp_nonce_field(basename(__FILE__), "mu-meta-box-nonce");

Add 'error' callback (just like 'success') this way:以这种方式添加“错误”回调(就像“成功”一样):

$.ajax({
   type: 'POST',
   url: 'submit1.php',
   data: $("#regist").serialize(),
   dataType: 'json',
   success: function() {
      $("#loading").append("<h2>you are here</h2>");
   },
   error: function(jqXhr, textStatus, errorMessage){
      console.log("Error: ", errorMessage);
   }
});

So, in my case I saw in console:所以,就我而言,我在控制台中看到:

Error:  SyntaxError: Unexpected end of JSON input
  at parse (<anonymous>), ..., etc.

The success callback takes two arguments:成功回调有两个参数:

success: function (data, textStatus) { }

Also make sure that the submit1.php sets the proper content-type header: application/json还要确保submit1.php设置了正确的内容类型标头: application/json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM