0

我正在尝试使用验证插件为远程验证器功能动态构建 JS。但由于某种原因,它没有将 JS 转换为对象,而是将其视为字符串并嵌入双引号。

前任:

我拥有的 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;

如何在$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;                     
                }
            }
        }
    }
} );

谢谢,

4

1 回答 1

2

JSON 是 javascript 的子集,您的示例不是有效的 JSON,因为它是 javascript 字符串。

评估它的唯一方法是使用 Function 或 eval

但是在不知道您要解决什么的情况下,我怀疑评估字符串是否是解决方案。

使用包含带有函数的 javascript 对象文字的字符串,以下将起作用。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"
于 2012-08-15T18:43:30.430 回答