[英]Converting JS String to JSON object
I am trying to construct a JS on the fly for a remote validator function using the validation plugin. 我正在尝试使用验证插件动态构建一个远程验证器函数。 but for some reason, it's not converting the JS as an object and is treating it as a string and embedding double quotes. 但由于某种原因,它没有将JS转换为对象,而是将其视为字符串并嵌入双引号。
Ex: 例如:
The PHP code I have is: 我的PHP代码是:
$remoteUrl = '/test/checkusername';
$remoteValidatorJs = "{url: '". $remoteUrl . "',
type: 'post',
async:false,
dataType: 'html',
beforeSend: function(){
alert('Validating Form Field');
},
complete: function(){
alert('Completed Validation of Form Field');
},
dataFilter: function(html) {
return html;
}
}";
$validation[ 'rules' ][ 'Name' ][ 'remote' ] = $remoteValidatorJs;
How do I frame or convert the JS in $remoteValidatorJs
variable so, it eventually looks like the content in the following "remote" section, when the array is printed: 如何在$remoteValidatorJs
变量中构造或转换JS,这样,当打印数组时,它最终看起来像下面“远程”部分中的内容:
$("#testForm").validate( {
"rules":{
"Name":{
"remote":{
url: '/test/checkusername',
type: 'post',
async:false,
dataType: 'html',
beforeSend: function(){
alert('Validating Form Field');
},complete: function(){
alert('Completed Validation of Form Field');
},
dataFilter: function(html) {
return html;
}
}
}
}
} );
Thanks, 谢谢,
JSON is a subset of javascript, your example isn't valid JSON as it's a javascript string. JSON是javascript的一个子集,您的示例不是有效的JSON,因为它是一个javascript字符串。
The only way to evaluate it would be to use Function or eval 评估它的唯一方法是使用Function或eval
But without knowing what you're trying to solve I doubt evaling a string is the solution. 但是,如果不知道你想要解决什么,我怀疑是否正在评估一个字符串是解决方案。
Using a string containing a javascript object literal with functions, the following would work. 使用包含带有函数的javascript对象文字的字符串,以下内容将起作用。 PS I haven't used your whole string :) PS我没用过你的整个字符串:)
var remoteUrl = "http://something.com";
var evalString =
[
'{url:"' + remoteUrl + '",',
'type:"post",',
'async:false}'
].join('')
evalString #// => "{url:"http://something.com",type:"post",async:false}"
var x= new Function("return " + evalString + ";")()
#// => Object
async: false
type: "post"
url: "http://something.com"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.