json_encode not working with a html string as value

前端 未结 8 1638
太阳男子
太阳男子 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.

    <?php
    /**
     * DEBUGGING NIGHTMARE
     * SO MUCH FUN, 10/10,
     */
    class Nightmare {
      protected $str;
      public function __construct($str) {
        $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.
    )
    
    0 讨论(0)
  • 2020-12-03 10:39

    You should call only prompt object of your array not all! like below:

    $("#typeForm").ajaxForm({
        success : function(html){
            var obj = $.parseJSON(html);
            alert(obj.prompt);
    }).submit(); 
    
    0 讨论(0)
提交回复
热议问题