我想發送一個JSON響應函數,並試圖在js中提醒該函數。以下是代碼。JSON響應函數名稱 - 不工作
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就是這樣被結構化文本。 – JohnP 2011-06-02 10:13:18