微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 从php发送错误消息到ajax

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

PHP

if (myString == '') {
    // Send "stringIsEmpty" error to ajax
} else if (myString == 'foo') {
    // Send "stringEqualsFoo" error to 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文件.我尝试使用回声解决方案答案说,但当我输出数据是什么(在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”){

解决方法:

只有在请求失败时才会调用错误函数,请参阅http://api.jquery.com/jQuery.ajax/

因此,如果从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";

有关更多信息,请参阅:How to return data from PHP to a jQuery ajax call

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐