Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将错误消息从php发送到ajax_Javascript_Php_Jquery_Ajax - Fatal编程技术网

Javascript 将错误消息从php发送到ajax

Javascript 将错误消息从php发送到ajax,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我试图从php向ajax发送“通知”或错误消息。我正在努力实现这样的目标: function triggerError(error) { if (error === "stringIsEmpty") { alert("Your string is empty!"); } else if (error === "stringEqualsFoo") { alert("Your string is equal to Foo!"); } } ph

我试图从php向ajax发送“通知”或错误消息。我正在努力实现这样的目标:

function triggerError(error) {
    if (error === "stringIsEmpty") {
        alert("Your string is empty!");
    } else if (error === "stringEqualsFoo") {
        alert("Your string is equal to Foo!");
    }
}
php:

if (myString == '') {
    // Send "stringIsEmpty" error to ajax
} else if (myString == 'foo') {
    // Send "stringEqualsFoo" error to ajax
}
ajax

$.ajax({
    url: $(this).attr("action"),
    context: document.body,
    data: formData, 
    type: "POST",  
    contentType: false,
    processData: false,
    success: function(){
        alert("It works");
    },
    error: function() {
        if(stringIsEmpty) {
            alert("String is empty");
        } else if(stringEqualsFoo) {
            alert("String equals Foo");
        }
    }
});
如何向ajax发送错误消息

更新

这是我的php文件。我尝试使用回答说的
echo
解决方案,但是当我输出
数据时(在ajax中),我得到
未定义的

<?php
$img=$_FILES['img'];
    if($img['name']==''){
        echo('noImage');
    }else{
        $filename = $img['tmp_name'];
        $client_id="myId";
        $handle = fopen($filename, "r");
        $data = fread($handle, filesize($filename));
        $pvars   = array('image' => base64_encode($data));
        $timeout = 30;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
        $out = curl_exec($curl);
        curl_close ($curl);
        $pms = json_decode($out,true);
        $url=$pms['data']['link'];
        if($url!=""){
            echo "<h2>Uploaded Without Any Problem</h2>";
            echo "<img src='$url'/>";
        }else{
            echo "<h2>There's a Problem</h2>";
            echo $pms['data']['error'];
            header("HTTP/1.1 404 Not Found");
        } 
    }
?>


我在
if($img['name']='')中添加了
echo(“noImage”)
,{
只有在请求失败时才会调用error函数,请参见

因此,如果您从PHP服务器返回响应,则不会触发错误函数。但是,您可以根据从PHP发送的响应定义一个函数来处理错误:

success: function(data){
        if (data === "stringIsEmpty") {
           triggerError("stringIsEmpty");
        } else if (data === "stringEqualsFoo") {
           triggerError("stringEqualsFoo");
        }
    },
然后你可以有这样的错误函数:

function triggerError(error) {
    if (error === "stringIsEmpty") {
        alert("Your string is empty!");
    } else if (error === "stringEqualsFoo") {
        alert("Your string is equal to Foo!");
    }
}
如果您请求post.php,只需返回一个字符串:

// Create a function to see if the string is empty
$funcOutput = isStringEmpty();
echo $funcOutput;
或者具体来说,例如:

echo "stringIsEmpty";
有关更多信息,请参阅:

当发送过程中调用失败时,将触发ajax方法的“错误”设置。错误如“超时”、“404”等

如果要控制服务器的某些响应,可以在“成功”设置中编写此代码

}))

PHP可以是这样的

if (myString == '') {
    echo '';
} else if (myString == 'foo') {
    echo 'foo';
}

问题是,如果您的php响应,那么从技术上讲这不是一个错误,必须在成功回调中处理

$.ajax({
    url: $(this).attr("action"),
    context: document.body,
    data: formData, 
    type: "POST",  
    contentType: false,
    processData: false,
    success: function(data){
        alert('The response is: '+data);
        if(data=="empty sting"){
            alert("The string is empty");
        } else if (data == 'foo') {
            alert("The string equals 'foo'");
        } else {
            alert("It works");
        }
    },
});
在PHP中:

if (myString == '') {
    echo('empty string');
} else if (myString == 'foo') {
    echo('foo');
}

因此,如果返回的字符串为空,或者等于“foo”,您可能会认为这是一个错误,但HTTP认为这是一个成功,您需要在“success”函数中查找这些字符串。

您可以通过在php中更改HTTP响应代码来触发jQuery错误处理程序。任何4xx或5xx错误都应该有效,但最好留在rfc中

PHP

// no output before the header()-call
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
echo "foo";
[...]
error: function(jqxhr) {
    alert(jqxhr.responseText)
}
[...]
jQuery

// no output before the header()-call
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
echo "foo";
[...]
error: function(jqxhr) {
    alert(jqxhr.responseText)
}
[...]

我已经尝试过使用jQueryAjax和PHP进行错误处理的引导模型

Javascript文件:

// add receipt data
        $('#insert_form').on("submit", function(event) {
            event.preventDefault();
            $.ajax({
                url: "includes/user-insert.inc.php",
                method: "POST",
                data: $('#insert_form').serialize(),
                async: true,
                beforeSend: function() {
                    $('#insert').val("Inserting");
                },
                success: function(data) {

                    $('#insert_form')[0].reset();
                    $('#add_reciept').modal('hide');
                    dataTable.ajax.reload(null, false);

                    if (data == "No") {
                        $('#alert-danger').addClass('alert alert-danger');
                        $('#alert-danger').html('<strong>Oh snap!</strong> Sorry, that Record wasn\'t Added <b>Try Again</b>');
                        $('#alert-danger').fadeIn().show();
                        setTimeout(function() {
                            $('#alert-danger').fadeOut("slow");
                        }, 8000);
                    } else if (data == "Yes") {
                        $('#alert-success').html('<strong>Well done!</strong> A Record has been Added.');
                        $('#alert-success').addClass('alert alert-info');
                        $('#alert-success').fadeIn().show();
                        setTimeout(function() {
                            $('#alert-success').fadeOut("slow");
                        }, 8000);
                    }


                },
                error: function(err) {
                    $('#alert-danger').addClass('alert alert-danger');
                    $('#alert-danger').html('<strong>Oh snap!</strong> Sorry, that Record wasn\'t Added <b>Try Again</b>');
                    $('#alert-danger').fadeIn().show();
                    setTimeout(function() {
                        $('#alert-danger').fadeOut("slow");
                    }, 8000);
                },
                complete: function(data) {
                    $('#insert').val("Insert");
                }
            });

        });

复制并粘贴代码,并进行适当的更改。你的问题还不清楚。我终于明白为什么会有奇怪的结果。有没有一种方法可以做到你的答案所说的,而不向网站输出任何内容?意思是,没有在实际的网站上显示“stringIsEmpty”?第一个答案不完整,直到我写完我的答案,我才看到第二个答案。第一个比你的更完整。谢谢!我试过你说的,它会显示在网站“
foo
”上,但它不会调用“警报”。我不想让它显示在网站上,我只想在ajax中做些事情,也就是提醒。)@Horay尝试编辑。如果不起作用,请告诉我第一个警报说什么。它说:“响应是:未定义”@Horay oh my。再次编辑。在第一次警报时,变量为response。你是说数据吗?谢谢!我试过你说的,它显示在网站“foo”上,但它不叫“警报”。我不希望它显示在网站上,我只想在ajax中做一些事情,也就是提醒。)编辑了答案,以便更清楚一点,如果您从PHP代码中返回“stringIsEmpty”,您可以在ajax端像那样处理它。如何从PHP代码中返回“stringIsEmpty”?通过一些示例再次调整。有关更多信息,请参阅:我尝试了你所说的,它显示在网站“foo”上,但它不称为“警报”。我不希望它显示在网站上,我只想在ajax中做一些事情,也就是警告。)您可以尝试从$.ajax调用中删除processData:false,这确保返回的数据作为查询字符串返回。否则我也不知道,我不知道你的整个代码结构是什么样子的(也就是你的php和js文件)。这就是我一直在寻找的,可能会帮助其他人。