javascript 如果不发送数据,Ajax 请求将无法工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20174057/
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
Ajax request won't work without sending data
提问by Stefano Kira
I'm trying to make an AJAX request to a PHP script for a simple logout. The PHP just does the following:
我正在尝试向 PHP 脚本发出 AJAX 请求以进行简单的注销。PHP 只执行以下操作:
<?php
session_start();
unset($_SESSION['autorizzato']);
$arr=array('result'=>"logout effettuato con successo");
$ris=json_encode($arr);
echo $ris;
?>
While the AJAX request looks something like this:
虽然 AJAX 请求看起来像这样:
$.ajax({
type: 'POST',
url: 'logout.php',
async: false
}).success(function(response){
if (response['result']=="logout effettuato con successo")
{
change();
}
else alert("Errore nel logout");
});
});
Problem is that resonse['result'] looks like it's unset. The curious thing is that if I add to the AJAX request a data string (like this:
问题是 resonse['result'] 看起来像是未设置。奇怪的是,如果我向 AJAX 请求添加一个数据字符串(如下所示:
$.ajax({
type: 'POST',
url: 'logout.php',
async: false,
dataType: 'json',
data: sendstr
}).success(function(response){
if (response['result']=="logout effettuato con successo")
{
change();
}
else alert("Errore nel logout");
});
});
where sendstr is a simple JSON stringified object. Anyone knows why? Thank you in advance :)
其中 sendstr 是一个简单的 JSON 字符串化对象。有谁知道为什么?先感谢您 :)
回答by Patato
your success function should do like
你的成功功能应该像
success(function(response){
var returnsult=JSON.parse(response);
if (returnsult.result=="logout effettuato con successo")
{
change();
}
else alert("Errore nel logout");
});
回答by Charlie Affumigato
Either you go this way:
要么你走这条路:
$.ajax({
type: 'POST',
url: 'logout.php',
async: false
}).success(function(response){
response=JSON.parse(response);//convert JSON string to JS object
if (response['result']=="logout effettuato con successo")
{
change();
}
else alert("Errore nel logout");
});
});
Or
或者
$.ajax({
type: 'POST',
url: 'logout.php',
async: false,
dataType: 'json' /* Tell jQuery you are expecting JSON */
}).success(function(response){
if (response['result']=="logout effettuato con successo")
{
change();
}
else alert("Errore nel logout");
});
});