json_encode not working with a html string as value

前端 未结 8 1694
太阳男子
太阳男子 2020-12-03 10:02

I am debugging this ajax for quite a time now. I have this on my jQUery file:

$(\"#typeForm\").ajaxForm({
    success : function(html){
        alert(html);
         


        
8条回答
  •  长情又很酷
    2020-12-03 10:36

    JSON doesn't play well with string output that comes out of magic method __toString() - it nearly impossible to json_encode() anything that even remotely touched something like this.

    str = $str;
      }
      public function __toString() {
        return $this->str;
      }
    }
    
    $test = new Nightmare('Hello Friends.');
    echo $test;
    > Hello Friends.
    
    // cooool, so let's JSON the hell out of it, EASY
    
    echo json_encode(['our_hello' => $test]);
    // This what you expect to get, right?
    > {"our_hello":"Hello Friends."}
    
    // HAHA NO!!!
    // THIS IS WHAT YOU GET:
    > {"our_hello":{}}
    
    
    // and this is why is that:
    
    var_dump($test);
    object(Nightmare)#1 (1) {
      ["str":protected]=>
      string(14) "Hello Friends."
    }
    
    print_r($test);
    Nightmare Object
    (
        [str:protected] => Hello Friends.
    )
    

提交回复
热议问题