Sending Javascript Functions Over JSON

有时需要通过json 传送函数,但是php的json_encode会带上引号。

下面是解决方案:

http://solutoire.com/2008/06/12/sending-javascript-functions-over-json/

PHP:

// Our sample array
$foo = array(
  'number'  => 1,
  'float'   => 1.5,
  'array'   => array(1,2),
  '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:
{
  "number":1,
  "float":1.5,
  "array":[1,2],
  "string":"bar",
  "function":function(){return "foo bar";}
}

  Javascript

new Ajax.Request('json_server.php', {
  method:'get',
  onSuccess: function(transport){
     var json = transport.responseText.evalJSON();
     alert(json.function()); // => alerts 'foo bar'
   }
});

  

posted @ 2015-05-28 14:02  rongbin  阅读(175)  评论(0编辑  收藏  举报