我有一个ajax函数,它将一些数据提交给我的PHP文件。在我的PHP文件中,我有一些检查,它与数据,我然后尝试发出警报,说出来。虽然我无法收到任何警报。所有发生的事情都在控制台 - > network-> submit.php->响应中显示应该发出警报的javascript。
这是我的Ajax,我知道它有效:
$('#submit').click(function() {
if(selectedImageArray.length <= 10){
$.ajax({
method: "POST",
url: "submit.php",
data: {selectedImageArray: selectedImageArray}
}).done(function( msg ) {
//alert( "Data Saved: " + selectedImageArray );
}); }else{
alert( "You can only trade up to 10 items at once." );
}
});
然后在submit.php中我做了一些检查,并且有这个:
if($QueueCount == 1){
Echo '<script language="javascript">';
Echo 'alert( "You already have an active trade, check your Steam profile.");';
echo '</script>';
}else{
Echo '<script language="javascript">';
Echo 'alert("You are currently in the trade Queue, you should receive a trade request soon.");';
echo '</script>';
}
这应该发出提醒,但它只是将<script language="javascript">alert( "You already have an active trade, check your Steam profile.");</script>
输出到网络标签中,就像我说的那样。
如何使这项工作从PHP文件中弹出警报?
答案 0 :(得分:2)
你试图从php输出javascript而不在你的ajax回调中输出它,将无法正常工作。
做你想做的最简单的方法是用你的php返回字符串,然后处理输出到你的javascript。
类似的东西:
if($QueueCount == 1){
Echo "You already have an active trade, check your Steam profile.";
}else{
Echo "You are currently in the trade Queue, you should receive a trade request soon.";
}
和javascript
$('#submit').click(function() {
if(selectedImageArray.length <= 10){
$.ajax({
method: "POST",
url: "submit.php",
data: {selectedImageArray: selectedImageArray}
}).done(function( msg ) {
alert(msg);
});
}else{
alert( "You can only trade up to 10 items at once." );
}
});
答案 1 :(得分:1)
你的javascript代码必须如下所示:
$('#submit').click(function() {
if(selectedImageArray.length <= 10){
$.ajax({
method: "POST",
url: "submit.php",
data: {selectedImageArray: selectedImageArray},
success: function(data,status){
eval(data)
}
});
}else{
alert( "You can only trade up to 10 items at once." );
}
});
你的php代码不应该声明脚本标签:
if($QueueCount == 1){
echo 'alert( "You already have an active trade, check your Steam profile.");';
}else{
echo 'alert("You are currently in the trade Queue, you should receive a trade request soon.");';
}
确保这是php文件的唯一输出。
此代码在开始生产之前还需要进行一些改进,例如在服务器端处理时回调错误,检查ajax是否由于网络问题和XSS保护而完全失败,列举一些。