jQuery 如何检查ajax响应是否包含特定值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14728664/
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
How to check if ajax response contains specific value
提问by Raju Kumar
How can you check to see whether the returned results contain a specific value?
如何检查返回的结果是否包含特定值?
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
//here i wanna check if the result return contains value "test"
//i tried the following..
if($(result).contains("test")){
//do something but this doesn't seem to work ...
}
}
},
});
});
});
回答by Kolby
Array.prototype.indexOf()
Array.prototype.indexOf()
if(result.indexOf("test") > -1)
Since this still gets up votes I'll edit in a more modern answer.
由于这仍然得到投票,我将编辑一个更现代的答案。
With es6 we can now use some more advanced array methods.
使用 es6,我们现在可以使用一些更高级的数组方法。
Array.prototype.includes()
Array.prototype.includes()
result.includes("test")
which will return a true or false.
result.includes("test")
这将返回真或假。
Array.prototype.some()
Array.prototype.some()
If your array contains objects instead of string you can use
如果您的数组包含对象而不是字符串,您可以使用
result.some(r => r.name === 'test')
which will return true if an object in the array has the name test.
result.some(r => r.name === 'test')
如果数组中的对象具有名称 test,则返回 true。
回答by nbrooks
The jQuery object does not have a contains
method. If you are expecting the returned result to be a string, you can check if your substring is contained within it:
jQuery 对象没有contains
方法。如果您希望返回的结果是一个字符串,您可以检查您的子字符串是否包含在其中:
if ( result.indexOf("test") > -1 ) {
//do something
}
If your result is JSON, and you're checking for a top-level property, you can do:
如果您的结果是 JSON,并且您正在检查顶级属性,您可以执行以下操作:
if ( result.hasOwnProperty("test") ) {
//do something
}
回答by Sedat Ba?ar
:contains() is a selector. u can check it from here http://api.jquery.com/contains-selector/
:contains() 是一个选择器。你可以从这里检查它http://api.jquery.com/contains-selector/
for this example u can use indexOf like below
对于此示例,您可以使用如下所示的 indexOf