XMLHTTPrequest无法正常工作

时间:2014-06-06 07:27:50

标签: javascript jquery ajax cors

我正在以两种方式向服务提出请求

1)通过XMLHTTPRequest->不工作

说 - >第1行中的JSON.parse意外数据结束col1

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    xhr = null;
  }
  return xhr;
}

function sign() {          
  var logincredentials = JSON.stringify({
   "username": "_username",
   "password": "_passsword"
  });

  var url = serviceurl; 
  var xhr = createCORSRequest('POST', url);
  if (!xhr) {
    alert('CORS not supported');
  }

  xhr.onload = function () {
    alert("success : ");
  };

  xhr.onerror = function () {
    alert("failed : ");
  };            
  xhr.setRequestHeader('Content-Type', 'application/jsonrequest; charset=UTF-8');
  xhr.send(logincredentials);
}

enter image description here

2)JQuery Ajax工作正常

function signJQ() {
  var userData = JSON.stringify({
    "username": "_username",
    "password": "_password"
  });

  $.ajax({
    type:"POST",
    url:"serviceurl",
    contentType: "application/json",
    dataType: "json",
    data:userData,
    success: function(data) {
      alert("success: " + JSON.stringify(data));
    },
    error: function(data) {
      alert("Failed: " + JSON.stringify(data));
    }
  });
}

两种情况可能有什么不同?

3 个答案:

答案 0 :(得分:0)

有一个拼写错误:

xhr.setRequestHeader('Content-Type', 'application/jsonrequest; charset=UTF-8');

当然应该是:

xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

答案 1 :(得分:0)

使用网址附加参数,"?username = _username& password = _passsword"

function sign() {          

            var logincredentials = "?username=_username&password=_passsword";


            var url = serviceurl; 

            var xhr = createCORSRequest('POST', url + logincredentials );
            if (!xhr) {
                alert('CORS not supported');
            }

            xhr.onload = function () {
                alert("success : ");

            };

            xhr.onerror = function () {
                alert("failed : ");

            };          
            xhr.setRequestHeader('Content-Type', 'application/jsonrequest; charset=UTF-8');
            xhr.send();

        }

您还需要功能createCORSRequest()

答案 2 :(得分:0)

尝试下面给出的代码段可能适用于您的情况:

  

function createXMLHTTPObject(){

var xmlhttp = false;
for (var i=0;i<XMLHttpFactories.length;i++) {
    try {
        xmlhttp = XMLHttpFactories[i]();
    }
    catch (e) {
        continue;
    }
    break;
}
return xmlhttp; 
     

}

使用请求:

  

function createCORSRequest(method,url){
   var xhr = createXMLHTTPObject();

 xhr.open(method, url,true);
 xhr.setRequestHeader("Accept", "application/json");
 xhr.setRequestHeader("Content-Type", "application/json");
 xhr.onreadystatechange=function()
{
     if (xhr.readyState)
     {
         if(xhr.status==200){
             request.success(xhr.responseText);
         }else if(xhr.status!=200){
             request.error(xhr.responseText)
         }
     }
 }
 xhr.send(body); 
     

}