PHP json_encode and javascript functions

后端 未结 9 1403
别跟我提以往
别跟我提以往 2020-12-06 04:28

I need to encode a javascript function into a JSON object in PHP.

This:

$function = \"function(){}\";
$message = \"Hello\";

$json = array(   
               


        
相关标签:
9条回答
  • 2020-12-06 04:57

    As Jani said, this is not possible directly with JSON, but this might help you: http://web.archive.org/web/20080828165256/http://solutoire.com/2008/06/12/sending-javascript-functions-over-json/

    0 讨论(0)
  • 2020-12-06 05:02

    You can try this:

    var json_string = '{"message":"Hello","myfunc":"function(){ alert(this.message) }"}';
    var json_string = JSON.parse(json_string, function(k,v){
        if(typeof v == 'string' && /function\(\)\{/.test(v)){
            return eval(k+' = '+v); 
        }else{
            return v
        }
    });
    
    0 讨论(0)
  • 2020-12-06 05:03

    This function can also help:

    function jsonify($var){
    return str_ireplace(array("'function",'"function',"}'",'}"'),array("function",'function',"}",'}'),json_encode($var));
    }
    

    Taken from here: http://network.convergenceservices.in/forum/105-uknowva-development/4710-introducing-convhelperjsonify-in-uknowva-251.html#4710

    0 讨论(0)
提交回复
热议问题