2014-03-27 39 views
0

我需要從服務器端從使用ajax POST在客戶端(Javascript)中創建的URL使用JSON對象。在沒有jQuery的JavaScript中的Ajax POST

var oReq = new XMLHttpRequest(); 
oReq.open("POST", url, true); 
oReq.responseType = "json"; 
oReq.onload = function(e) { 
    var jsonObj = oReq.response; 
    /* ... */ 
} 

我在function(e)裏面應該用什麼?

我不應該在這裏使用jquery。

+0

我用這個http://stackoverflow.com/questions/6132796/how-to-make-a-jsonp-request-from-javascript-without-jquery爲同樣的問題。你的服務器必須支持JSONP,雖然 –

+0

chouck這個http://blog.mgechev.com/2011/07/21/ajax-jquery-beginners/ – radia

回答

1

您需要send()您的要求。

this (slightly adjusted) example:

var oReq = new XMLHttpRequest(); 

oReq.open("POST", url, true); 
oReq.responseType = "json"; 
oReq.onload = function(e) { 
    var jsonResponse = oReq.response; // not responseText 
    /* ... */ 
} 
oReq.send(); 
+0

我想在這裏做一個帖子在一個URL。 – Arun

+0

如果你想發佈,把你想發佈的內容放在'.send'中。這是正確的迴應。 –

-1

這是一個功能我寫&始終使用AJAX請求,帖子...無論

function ajax(a,b,e,d,f,g,c){ 
    // url,callback,type(get),FormData(null),uploadProgress,progress 
    c=new XMLHttpRequest; 
    !f||(c.upload.onprogress=f); 
    !g||(c.onprogress=g); 
    c.onload=b; 
    c.open(e||'get',a); 
    c.send(d||null) 
} 

我認爲只有通過鉻removeing responseType='json';支持responseType='json'; 你可以通過使用

JSON.parse() 

這樣:

JSON.parse(oReq.response) 

擺脫這個AJAX響應呼叫時,可以3種方式

1.In我而言/或您的

c.response 
//your 
oReq.response 

2,採用這種

之間選擇
this.response // i always use this. 

3.e.目標

e.target.response 

AJAX功能描述:

此AJAX功能6個可用參數

URL,回調,類型(GET或POST),FORMDATA(或空),上傳進度,進度

只需要2個urlcallback(簡單的獲取請求)

ajax('url',function(){console.log(this.response)}) 
// it's better to use a function reference to avoid memory leaks 
// like 
function cb(){console.log(this.response)}; 
ajax('url',cb) 
你的情況

使用後

,所以你需要4個參數

urlcallbacktype(post in your case)formdata

這樣:

ajax('url',callbackFunction,'post',fd); 

其中fd是建立在2種方式

var fd=new FormData(); 
fd.append('key','value'); 
ajax('url',callbackFunction,'post',fd); 

,或者您也可以張貼整個形式

var fd=new FormData(document.getElementsByTagName('form')[0]); 
ajax('url',callbackFunction,'post',fd); 

另外,您還可以添加一個進度事件函數

function progress(e){ 
console.log(e.loaded/e.total*100) 
} 

同爲上傳進度

和回調函數就像那樣

function callbackFunction(e){ 
console.log(e.target.response); 
console.log(this.response); 
console.log(c.response); 

// without the reponsetype 

console.log(JSON.parse(e.target.response)); 
console.log(JSON.parse(this.response)); 
console.log(JSON.parse(c.response)) 
} 

如果您有任何問題,請詢問。