2012-10-22 87 views
0

不幸的是,我沒有得到任何東西,只是看起來像jQuery結果。我正在尋找通過AJAX傳遞參數的正確方法,請勿使用舊的瀏覽器回退,但不需要庫。如果有另一個線程,我已經錯過了,請鏈接=)Ajax - 參數不通過 - 沒有jQuery

我使用$,但它是一個自定義對象/不管,而不是jQuery。

$.ajax({ 
    't':'POST', 
    'u':e, 
    'd':{ajax:'1'}, 
    's':function(data){ 
     console.log(data.response); 
     document.getElementById('mainc').innerHTML = data.response; 
    }, 
    'e':function(data){ 
     console.log(data); 
    } 
}); 

的呼叫:

$.ajax = function(a){ 
if(!a.u){return false;}; 
a.t=a.t||"GET"; 
typeof a.a=='undefined'?true:a.a; 
a.e=a.e||function(){return false;}; 
a.s=a.s||function(){return true;}; 
var x=new XMLHttpRequest(); 
x.open(a.t,a.u,a.a); 
x.onreadystatechange=function(){ 
    if(x.readyState===4){ 
     if(x.status===200){ 
      a.s(x); 
     }else{ 
      a.e(x); 
     } 
    } 
}; 
a.t==="post" ? x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") : null; 
x.send(a.d); 

}

x.send(a.d)應通過{ajax:'1'}。我試過{'ajax':'1'},只是'ajax=1'。不知道爲什麼我嘗試傳遞的參數都沒有變成服務器端。我非常確定這些參數沒有打到服務器上,儘管請求似乎沒有問題地發送和接收。

+0

你的代碼進行模糊處理使得它的痛苦,試圖瞭解這意味着什麼的事實。如果您需要幫助,請使您的代碼可讀。如果你使用它,除了你以外,沒有人能夠維護那些代碼。每天。永遠。 – PatrikAkerstrand

回答

1

XMLHttpRequest.send()如果您設置了x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"),則不接受javascript/JSON對象。

你應該格式化爲url編碼變量這裏提到:

Query-string encoding of a Javascript Object

或使用x.setRequestHeader("Content-Type", "application/json")像另一個答案建議。

另外:

a.t==="post"a.t==="POST",因爲它不會改變,因爲區分大小寫檢查的請求報頭。

全部工作的代碼(與urlencoded的數據):

$ = {} 

$.ajax = function(a){ 
if(!a.u){return false;}; 
a.t=a.t||"GET"; 
typeof a.a=='undefined'?true:a.a; 
a.e=a.e||function(){return false;}; 
a.s=a.s||function(){return true;}; 
var x=new XMLHttpRequest(); 
x.open(a.t,a.u,a.a); 
x.onreadystatechange=function(){ 
    if(x.readyState===4){ 
     if(x.status===200){ 
      a.s(x); 
     }else{ 
      a.e(x); 
     } 
    } 
}; 
a.t==="POST" ? x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") : null; 
x.send(a.d); 

}  

$.ajax({ 
    't':'POST', 
    'u':'/', 
    'd':"ajax=1", 
    's':function(data){ 
     console.log(data.response); 
     document.getElementById('mainc').innerHTML = data.response; 
    }, 
    'e':function(data){ 
     console.log(data); 
    } 
}); 
+0

謝謝!對「POST」有很好的解釋和良好的理解! –

1

嘗試設置請求頭

x.setRequestHeader("Content-Type", "application/json") 

檢查this出來。

+0

感謝您的鏈接! –