我有一张登记表,正在使用$。Ajax来提交。

这是我的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;        
    });
});

在我的submit1.php文件中,我检查了数据库中字段电子邮件地址和用户名的存在。 我希望显示一个错误消息,如果这些值存在而不刷新页面。

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


当前回答

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

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

其他回答

添加'error'回调函数(就像'success'一样):

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

以我为例,我在控制台看到:

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

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

在我的例子中,原因是结束标记与开始标记不匹配。

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

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

我犯了一个错误,试图直接使用这样的函数(success: 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;
  }

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

我遇到了同样的问题,我用这种方法解决了它: 我的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');
                }
            }
        })

好的。问题不在于json,而在于php响应。 之前:我的php回答是:

echo 'item';

现在:

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

现在我的成功工作。 PS.如果有什么地方不对,我很抱歉,但这是我在这个论坛上的第一个评论:)

在成功回调中放入alert()以确保它被调用。

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

为firefox安装firebug插件(如果还没有安装的话),并检查AJAX回调。您将能够看到响应,以及它是否收到一个成功的(200 OK)响应。您还可以在完整的回调中放入另一个alert(),它肯定会被调用。