从 PHP run via 返回错误。阿贾克斯?

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

Return errors from PHP run via. AJAX?

phpajaxreturn

提问by Bojangles

Is there a way to get PHP to return an AJAX error code if the PHP script fails somewhere? I was following a tutorial and typed this in to my PHP:

如果 PHP 脚本在某处失败,有没有办法让 PHP 返回 AJAX 错误代码?我正在学习教程并将其输入到我的 PHP 中:

$return['error'] = true;
$return['msg'] = "Could not connect to DB";

And all was well, until I realised it was JSON data. Is there a way to return errors using standard $_POST and returned HTML data (as in, trigger jQuery's AJAX error:event?

一切都很好,直到我意识到这是 JSON 数据。有没有办法使用标准 $_POST 返回错误并返回 HTML 数据(例如,触发 jQuery 的 AJAXerror:事件?

回答by Linus Kleen

I don't know about jQuery, but if it distinguishes between successful and unsuccessful (HTTP 200 OK vs. HTTP != 200) Ajax requests, you might want your PHP script respond with an HTTP code not equal to 200:

我不了解 jQuery,但如果它区分成功和不成功(HTTP 200 OK 与 HTTP != 200)Ajax 请求,您可能希望 PHP 脚本以不等于 200 的 HTTP 代码响应:

if ($everything_is_ok)
    {
        header('Content-Type: application/json');
        print json_encode($result);
    }
else
    {
        header('HTTP/1.1 500 Internal Server Booboo');
        header('Content-Type: application/json; charset=UTF-8');
        die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
    }

回答by Webist

$return = array();
$return['msg'] = "Could not connect to DB";

if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']  == 'XMLHttpRequest')
{
    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    header('Content-type: application/json');
    die(json_encode($return));
}

回答by Tangi

try this out. Hope it helps.

试试这个。希望能帮助到你。

<!-- This is index.php --->
<html>
        <head>
            <script src="js/jquery.js" type="text/javascript"></script><!-- link to jQuery -->
            <script language="javascript"> 
            $(document).ready(function () {
                $('input#send').click(function(){
                    /* Empty div#error and div#result incase they contain info from the last submission */
                    $('#error').empty('');
                    $('#result').empty('');
                    /* Client-side validation */
                    var name = $("input#name").val();
                    var age = $("input#age").val();
                    if (name==''){
                        alert('Insert your name.');
                    }
                    else if (age==''){
                        alert('Insert your age.');
                    } else { 
                        var params = 'name=' + name + '&age=' + age;   
                        $.ajax({        
                             url:'b.php',        
                             type:'post',                 
                             dataType:'html',            
                             data:params,
                             cache: false,            
                             success:data     
                             }); 
                        function data (html) {
                            var $html = $( html ); // create DOM elements in a jQuery object
                            /* Return errors from 'b.php' */
                            $html.filter('#err').appendTo("#error");
                            /* Return valid Post */
                            $html.filter('#res').appendTo("#result");
                            /* Clear name input */
                            $('input#name').val('');
                            /* Clear age input */
                            $('input#age').val('');
                        }
                    }
                }); 
            }); 
            </script>
            <style type='text/css'>
                #error{
                    color:maroon;
                    font-weight:bold;
                }
                #result{
                    color:green;
                    font-weight:bold;
                }
            </style>
        </head>
        <body>
            <div id="error"></div><!-- View Errors -->
            <div id="result"></div><!-- View valid Post -->
            <input type='text' name='name' id="name" value='' /><br/ >
            <input type='text' name='age' id="age" value='' /><br/ >
            <input type='submit' name='send' id="send" value='Send' />
        </body>

<?php
/* This is b.php */
if(($_POST['name']=='')||($_POST['age']=='')){
    $error = '<div id="err">Error: Fill in ALL fields.</div>';
} elseif(is_numeric($_POST['name'])){
    $error = '<div id="err">Error: Name should NOT contain numbers.</div>';
} elseif(!is_numeric($_POST['age'])){
    $error = '<div id="err">Error: Age should ONLY contain numbers.</div>';
} else{
    $result = '<div id="res">Hi '.$_POST['name'].', you are '.$_POST['age'].' years old.</div>';
}
echo $error;
echo $result;
?>

回答by Binayak Banerjee

For simple transfer of data from PHP to AJAX, Json encoding or key value pairs are not always necessary. It can be simply done using string handling.

对于从 PHP 到 AJAX 的简单数据传输,Json 编码或键值对并不总是必要的。它可以简单地使用字符串处理来完成。

A sample code explaining this functionality is below.

下面是解释此功能的示例代码。

    $query = "SELECT email FROM login WHERE email = '". mysqli_real_escape_string($conn,$email) ."' AND password = '". mysqli_real_escape_string($conn,$pass) ."'" ;

    $result = mysqli_query($conn,$query);
    $row=mysqli_fetch_row($result);

    $row_cnt = mysqli_num_rows($result);
    $s_email = $row[0];

    if ($row_cnt == 1) {
        $response="success";
    } else {
    $response = "Invalid Credentials";
    }

    $conn->close();

    $_SESSION["email"]= $s_email;
    echo $response;

This code shows how a 'success' response is sent back to ajax calling the php code. Further in ajax the following could be done to retrieve the response.

此代码显示如何将“成功”响应发送回调用 php 代码的 ajax。进一步在 ajax 中,可以执行以下操作来检索响应。

    $.ajax({ type : 'POST',
          data : {email: $('#email').val(), password: $('#pass').val()},
          url  : 'login.php',              
          success: function (data) {
            if(data == 'success'){  //the value echoed from php can be stored in the data variable of ajax
                window.location.assign('upload.php');
            }
            else{
                alert(data);
            }
          },
          error: function ( xhr ) {
            alert("error");
        }
    });

The above concept can be extended to return MULTIPLE VALUES also. This method allows simple tranfer of data from PHP to AJAX in a string format.

上述概念也可以扩展为返回 MULTIPLE VALUES。此方法允许以字符串格式将数据从 PHP 简单传输到 AJAX。

We have to follow a simple step of echoing everything we need to send as a response from the php to ajax, seperated by a unique seperator.

我们必须遵循一个简单的步骤,将我们需要发送的所有内容作为响应从 php 发送到 ajax,并由唯一的分隔符分隔。

    echo $response.#;
    echo $email.#;
    echo $password.#;
    echo "Hello".#;
    echo "World";

Then the variable data in ajax could be simply retrieved as in the above example and a simple function like,

然后可以像上面的例子一样简单地检索 ajax 中的变量数据和一个简单的函数,例如,

    var res = data.split("#");

data, being the variable within ajax. The res array can then be used within js for whatever purpose we need.

数据,作为ajax中的变量。res 数组然后可以在 js 中用于我们需要的任何目的。