【问题标题】:SyntaxError: Unexpected token W in JSON at position 0SyntaxError:位置 0 处 JSON 中的意外标记 W
【发布时间】:2019-03-16 07:40:02
【问题描述】:

我正在使用 JavaScript 中的 API 发送 POST 请求,并且我已经使用以下方法发出了许多 POST 请求,但现在显示错误: SyntaxError:JSON 中位置 0 处的意外标记 W

这是我的代码-

function updateAlertSetting(data_json, callback){

var firebase_token = getCookie("firebase_token");
if(firebase_token===null){
    window.location.href="login.html";
    return;
}
var base_64_firebase_token = btoa(firebase_token);

console.log(typeof data_json);  // Object
console.log(data_json);         // prints the data_json

$.ajax(
    {
        type: 'POST',
        url: getApiURL(28),
        data: {
                "alertSetting_value": data_json.alertSetting_value,
                "alertSetting_name": data_json.alertSetting_name,
                "firebase_token": data_json.firebase_token
              },
        headers: { "Authorization": "Basic " + base_64_firebase_token },
        success : function(newData){
            callback(newData);
        },
        error: function (xhr,ajaxOptions,throwError){
            console.log(throwError);
            console.log("Error!!!");
        }
    }
);
}

【问题讨论】:

  • 检查 devtools 网络选项卡以检查请求/响应数据
  • 你一定要发表你的回应
  • @0xc14m1z 我已经在做 POST 请求了。请看那个。
  • @jro 你想检查什么或者我应该告诉你更多关于这个问题的信息?
  • 转到 devtools 的网络选项卡,找到请求并将响应代码和响应数据(如果有)添加到您的问题中

标签: javascript ajax http-post


【解决方案1】:

我是通过以下代码做到的:

var xmlhttp;
    try{
        xmlhttp = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                //Browser doesn't support ajax  
                alert("Your browser is unsupported");
            }
        }
    }       
    if(xmlhttp){
        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState===4 && xmlhttp.status===200) {
                callback(xmlhttp.responseText);
            }
            if(xmlhttp.status === 404){
                alert("It couldn't connect to the server.");
            }               
        }
        xmlhttp.open("POST",getApiURL(28),true);
        xmlhttp.setRequestHeader("Authorization","Basic " + base_64_firebase_token);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send("alertSetting_value="+data_json.alertSetting_value+"&alertSetting_name="+data_json.alertSetting_name+"&firebase_token="+data_json.firebase_token);
    }

现在这正在工作,感谢@jro。

【讨论】:

    猜你喜欢
    • 2020-07-02
    • 2021-05-06
    • 1970-01-01
    • 2017-12-24
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    相关资源
    最近更新 更多