You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP登录应用JSON响应触发SyntaxError错误求助

JSON.parse: Unexpected Character Error in PHP Login AJAX Response (Resolved)

I was stuck with a frustrating SyntaxError: JSON.parse: unexpected character error in Firefox when my PHP login app returned JSON via AJAX. I tried all the usual fixes but none worked:

  • Tweaking and even disabling the mbstring extension
  • Saving files as "UTF-8 without BOM" in Notepad++
  • Adding ob_clean() to clear output buffers

Relevant Code Snippets

PHP Login Logic:

if($veri[0] == 'TRUE' && $veri[1] == 'TRUE'){
    if(isset($_POST['js']) && $_POST['js'] == 'ajax'){
        header('Content-type: application/json');
        echo json_encode(array('login'=>true,'redi'=>true,'url'=>'./?p=publicar'));
        exit();
    }
}

JavaScript AJAX Handler:

function ajax(){
    this.respuesta;
    this.ajaxCall = function(f, method, url, callback){
        try{
            var x = new XMLHttpRequest();
            x.open(method, url);
            x.onreadystatechange = function(){
                if(x.status == 200 && x.readyState == 4){
                    this.respuesta = x.responseText;
                    if(x.getResponseHeader('Content-type') == 'text/html'){
                        callback(this.respuesta);
                    }else if(x.getResponseHeader('Content-type') == 'application/json'){
                        this.respuesta = JSON.parse(x.responseText);
                        if(this.respuesta.login == true){
                            window.location = this.respuesta.url;
                            document.removeEventListener('keydown', function(){
                                if(evt.keyCode == 27){ }
                            });
                        }
                    }
                }else{
                    this.respuesta = false;
                }
            }
            if(method=='GET'){
                x.send(f);
            }else if(method=='POST'){
                x.send(f);
            }
        }catch(e){ pass('Error'); }
    }
}

The Fix That Worked

After hours of troubleshooting, the solution ended up being straightforward:

  1. Copy the code from each PHP page into a new, blank PHP file created in Dreamweaver or Notepad++
  2. Use the editor's "Convert to UTF-8 WITHOUT BOM" feature on the new file
  3. Save all these fresh files into a completely new folder (to avoid any residual hidden characters or corrupted metadata from the original directory)

This wiped out the invisible unexpected characters that were breaking the JSON parsing.

内容的提问来源于stack exchange,提问作者Shampoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:28:31