【问题标题】:function name in json response - not workingjson响应中的函数名-不起作用
【发布时间】:2011-06-02 10:08:18
【问题描述】:

我正在尝试在 JSON 响应中发送一个函数,并尝试在 js 中提醒该函数。下面是代码。

JS:

$('input').keyup(function(){
    $.ajax({
        type: "POST",
        url: "sample.php",
        dataType : 'json',
        data: 'val='+$('input').val(),
        success: function(response){

         var json = transport.responseText.evalJSON();
         alert(json.function()); // => **should alert 'foo bar' - but not**
        }
    });
});

PHP:

<?php
// Our sample array
$foo = array(
  'string'  => 'bar',
  'function'=> 'function(){return "foo bar";}'
);
$value_arr = array();
$replace_keys = array();
foreach($foo as $key => &$value){
  // Look for values starting with 'function('
  if(strpos($value, 'function(')===0){
    // Store function string.
    $value_arr[] = $value;
    // Replace function string in $foo with a 'unique' special key.
    $value = '%' . $key . '%';
    // Later on, we'll look for the value, and replace it.
    $replace_keys[] = '"' . $value . '"';
  }
}

// Now encode the array to json format
$json = json_encode($foo);

/* $json looks like:
{
  "number":1,
  "float":1.5,
  "array":[1,2],
  "string":"bar",
  "function":"%function%"
}
*/
// Replace the special keys with the original string.
$json = str_replace($replace_keys, $value_arr, $json);

// Send to to the client
echo $json;

/* This echoes the following string:
{
  "string":"bar",
  "function":function(){return "foo bar";}
}
*/
?>

我在上面做错了什么?任何帮助表示赞赏。

【问题讨论】:

  • 永远记住 json 只是结构化的文本。

标签: php jquery json


【解决方案1】:

JSON 没有任何函数表示。这是一种数据符号。即使你欺骗 PHP 发送一个函数(就像你试图做的那样),客户端上的 proper JSON 反序列化器也会抛出异常(理想情况下)。一些非常幼稚的依赖eval 的函数可能会通过该函数,但此时,您不是在使用 JSON,而是在使用 JavaScript。

如果你想发回code,你需要发回JavaScript。

另外,在这一行:

alert(json.function());

...您有语法错误。 function 是 JavaScript 中的保留字。您不能将其用作属性名称文字。如果您创建一个名为“function”的属性(您可以,但可能不应该),要访问它,您必须使用字符串表示法来访问属性:

alert(json["function"]());

另见Gaby's answer,您似乎在其中混入了一些原型代码(evalJSON)。

【讨论】:

    【解决方案2】:

    函数不是 JSON 中的有效数据类型。您可以做的是将函数表达式作为字符串发送:

    {
      "string": "bar",
      "function":"function(){return \"foo bar\";}"
    }
    

    然后使用eval:

    var f = eval(response['function']);
    

    但我不建议这样做。这是可怕的,复杂的,不容易理解或维护。这基本上是你能做的最糟糕的事情了。

    你想解决什么问题?


    如果您必须从服务器发送 JavaScript,那么就这样做(不要返回 JSON),并将script 用作dataType

    【讨论】:

    • eval 和函数编码为 json 中的代码字符串。太可怕了:(
    • +1 值可以是双引号中的字符串,也可以是数字,也可以是 true 或 false 或 null,也可以是对象或数组。这些结构可以嵌套。 json.org
    【解决方案3】:

    你显然在使用来自http://solutoire.com/2008/06/12/sending-javascript-functions-over-json/的代码

    但他们使用的是prototype 而不是jQuery ..

    transport.responseText.evalJSON(); 行在 jQuery 中没有任何意义..

    还可以查看http://json.org/,您会发现函数不应该使用 JSON 格式。有关更多说明,请阅读 Is it valid to define functions in JSON results?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      相关资源
      最近更新 更多