Javascript Jquery ajax 数据转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11684024/
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
Jquery ajax data convert to string
提问by comebal
I have a problem with my jquery ajax. I have this code:
我的 jquery ajax 有问题。我有这个代码:
$.ajax({
url: '/users/validatepassword/'+current,
success: function(data){
status = data;
},
async: false
});
if(status == "Password correct")
{
//do something
}
Basically, I want to capture the "data" that was returned on "success". But I cannot make a way for the if statement to work. I am think the "data" was not a string so I cannot make a comparison.
基本上,我想捕获“成功”返回的“数据”。但是我无法让 if 语句起作用。我认为“数据”不是字符串,所以我无法进行比较。
采纳答案by mrsrinivas
Define statusoutside ajax call. then access that everywhere.
在 ajax 调用之外定义状态。然后到处访问。
var status = '';
$.ajax({
url: '/users/validatepassword/'+current,
async: false,
dataType: "json",
success: function(data){
status = data;
},
});
if(status == "Password correct")
{
//do something
}
At users/validatepassworduse json_encode()
在用户/验证密码使用json_encode()
echo json_encode("Password correct");
回答by Pradeeshnarayan
Try status checking condition inside the ajax code.
在 ajax 代码中尝试状态检查条件。
$.ajax({
url: '/users/validatepassword/'+current,
success: function(data){
status = data;
if(status == "Password correct")
{
//do something
}
},
async: false
});
if the condition is outside ajax, It will execute before the ajax return.
如果条件在ajax之外,它会在ajax返回之前执行。
回答by Antguider
You can try like this,
你可以这样试试
var response = $.ajax({
url: '/users/validatepassword/'+current,
async: false
}).responseText;
if(response == "Password correct")
{
//do something
}
回答by repsaj
You see you should process the message within the success function not from outside.
你看你应该在成功函数中处理消息,而不是从外部处理。
var status = '';
$.ajax({
url: '/users/validatepassword/'+current,
async: false,
success: function(data){
status = data;
if(status == "Password correct")
{
//do something
}
}
});
回答by GOK
@Comebal: Buddy this is what u need to do:
@Comebal:伙计,这是你需要做的:
Firstly remove the async:false
首先删除 async:false
$.ajax({
url: '/users/validatepassword/'+current,
success: function(data){
//alert(data);
if(data == "Password correct")
{
//do something
}
}
});
Then, the major part is make sure data from ajax page is "Password correct" or else u can't "do something"... :)
然后,主要部分是确保来自 ajax 页面的数据是“密码正确”,否则你不能“做某事”...... :)