【发布时间】:2026-02-15 19:00:01
【问题描述】:
我正在尝试从 php 向 ajax 发送“通知”或错误消息。我正在尝试实现这样的目标:
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 解决方案答案说,但是当我输出data 是什么时(在ajax 中),我得到undefined:
<?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")
【问题讨论】:
-
复制并粘贴代码并进行适当的更改。您的问题不清楚。
-
我终于明白了为什么它会给出奇怪的结果。有没有办法在不向网站输出任何内容的情况下执行您的回答?意思是,没有在实际网站上显示“stringIsEmpty”?
标签: javascript php jquery ajax