如何检查返回的结果是否包含特定值?
$(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 ...
}
}
},
});
});
});
Run Code Online (Sandbox Code Playgroud)
Kol*_*lby 14
if(result.indexOf("test") > -1)
Run Code Online (Sandbox Code Playgroud)
由于这仍然得到了投票,我将在一个更现代的答案编辑.
使用es6,我们现在可以使用一些更高级的数组方法.
result.includes("test")
这将返回真或假.
如果您的数组包含对象而不是字符串,则可以使用
result.some(r => r.name === 'test')
如果数组中的对象具有名称test,则返回true.
nbr*_*oks 11
jQuery对象没有contains
方法.如果您希望返回的结果是字符串,则可以检查您的子字符串是否包含在其中:
if ( result.indexOf("test") > -1 ) {
//do something
}
Run Code Online (Sandbox Code Playgroud)
如果您的结果是JSON,并且您正在检查顶级属性,则可以执行以下操作:
if ( result.hasOwnProperty("test") ) {
//do something
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
35094 次 |
最近记录: |