jQuery技术:Jquery AJAX从PHP返回

使用此Jquery AJAX方法的新手。 所以我正在使用Jquery进行AJAX调用,在我的PHP脚本中,我在从数据库中检查条件为真,然后传入我的数据字符串并绑定变量,然后执行该查询。 脚本和数据库插入都正常工作。

我的问题是,如何从我的PHP脚本返回时在我的AJAX调用中显示错误消息?

JS


$.ajax({ type: "POST", url: 'submit_form.php', data: dataString, error: function() { alert('Error'); }, success: function() { alert('Success'); } }); 

SUBMIT_FORM.PHP

 if ( count of rows in db < x ) { return false; exit(); } 

如果这个条件为真,我想停止执行我的脚本并在我的AJAX函数中执行错误条件。


 elseif ($stmt = $mysqli->prepare("INSERT INTO blah (stuff, morestuff) values (?, ?)")) { /* Bind our params */ $stmt->bind_param("ss", $param1, $param1); /* Set our params */ $param1= $_POST["name"]; $param2= $_POST["email"]; /* Execute the prepared Statement */ $stmt->execute(); /* Close the statement */ $stmt->close(); } 

如果第一个条件为false,那么我想在我正在进行的ajax调用中返回success函数。

    要调用$.ajax的error handling程序,可以在PHP中编写以下代码(对于FastCGI):

     header('Status: 404 Not found'); exit; 

    或者,如果您不使用FastCGI,请使用header('HTTP/1.0 404 Not Found')

    我个人不会使用这种方法,因为它模糊了Web服务器错误和应用程序错误之间的界限。

    你最好使用错误机制,例如:

     echo json_encode(array('error' => array( 'message' => 'Error message', 'code' => 123, ))); exit; 

    在成功处理程序中:

     if (data.error) { alert(data.error.message); } 

    如果要在jquery中执行error命令,可以尝试使用: throw new Exception("Invalid"); 你的PHP代码里面(错误应该调用)。

    这将导致http服务器将错误代码500返回到您的javascript代码。

    你的概念是错误的。 错误条件意味着ajax调用中的错误将您的代码更改为此

     $.ajax({ type: "POST", url: 'submit_form.php', data: dataString, error: function() { alert('Error'); //here the error is the error in ajax call.eg failing to call or a 404..etc }, success: function(msg) { if(msg=='error'){ alert('Error'); //this is the error you are looking for }else{ alert('Success'); } } }); 

    你的PHP

     if ( count of rows in db < x ) { echo 'error'; //this is enough exit; } 

    根据jquery的说法,我认为你对jquery错误设置感到困惑

    error:请求失败时要调用的函数。

    所以你的错误代码只会因为以下原因被触发

    404错误 – 找不到ajax文件错误

    500错误 – ajax内部系统错误

    需要了解更多jQuery教程分享Jquery AJAX从PHP返回,都可以关注jQuery技术分享栏目---计算机技术网(www.ctvol.com)!

      以上就是jQuery教程分享Jquery AJAX从PHP返回相关内容,想了解更多jQuery开发(异常处理)及jQuery教程关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/jquerytutorial/982108.html

      (0)
      上一篇 2021年12月13日
      下一篇 2021年12月13日

      精彩推荐