Uncaught SyntaxError: Unexpected token in JSON at position 0

后端 未结 3 1302
名媛妹妹
名媛妹妹 2021-01-27 09:59

With some help, I have managed to make a form that validates and confirms user password before adding the user to the database. I have encountered some problem as the data of th

相关标签:
3条回答
  • 2021-01-27 10:24

    Have you set your content-type in your php?

    header('Content-Type: application/json');
    

    Also you don't need to put "true" in quote marks, when the json gets to your php script, once you run json_decode, php will recognise it as a boolean.

    0 讨论(0)
  • 2021-01-27 10:28

    First of all, jQuery can decode JSON automatically for you (and it will make its best to guess). Trying to do it manually only makes your code more verbose and error-prone. However, you don't give it any hint. Nothing in the code you've shared gives any clue about your intention to use jQuery.

    All the phases where you can do so, in chronological order:

    1. Report data type from web server. If you happen to be using Apache:

      <Files "confirm3.php">
          ForceType application/json
      </Files>
      
    2. Report data type from PHP:

      header('Content-Type: application/json');
      
    3. Tell jQuery that you expect JSON:

      url: "confirm3.php",
      method: "POST",
      dataType: "json",
      data: { Submit: "true" },
      success: function(response) {
          console.log(data); // Already decoded (don't use alert to debug!)
      }
      

    You can certainly omit almost any step, but not all.

    Secondly, if you get a JSON parse error the very first you need to check is whether the response is valid JSON. The most straightforward way to see it is using the browser developer tools, more specifically the "Network" pane.

    0 讨论(0)
  • 2021-01-27 10:38

    Use this in my case there was some null bytes so this i figured out and it fixed my issues.

    var data3 = data.substring(data.lastIndexOf("{")+1,data.lastIndexOf("}"));
          count = $.parseJSON("{"+data3+"}");
          alert( count.firstname ); // firstname is the key so you can use anything to test it.
    
    0 讨论(0)
提交回复
热议问题