2014-03-27 4 views
0

ajax POST를 사용하여 클라이언트 측 (자바 스크립트)에서 생성해야하는 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를 사용했습니다. –

+0

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

답변

1

귀하의 요청은 send()입니다.

여기

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

this (slightly adjusted) example: 내가 항상 아약스 요청, 게시물 ...

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) 
} 

난 단지 크롬 responseType='json';을 removeing하여 responseType='json'; 를 지원하는지 생각대로 사용 &을 쓴 함수 참조 사용하여 json 응답을 얻을 수 있습니다.

JSON.parse() 

그렇게 :

JSON.parse(oReq.response) 

는이

을 2.Using 3 가지 방법

1.In 내 경우/또는

c.response 
//your 
oReq.response 

중에서 선택할 수 있습니다 호출이 아약스의 응답을 얻기 위해

this.response // i always use this. 

3.e.가

이 AJAX 함수 6 개 가능한 파라미터

URL 콜백, 유형 (GET 또는 POST), FormData (는 null) uploadProgress가

진행했다 :

e.target.response 

AJAX 기능 설명 타겟팅

2 개만 필요합니다. urlcallback (간단히 요청 받기)

구축이다

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

: 귀하의 경우

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) 

10 당신은 그래서 당신은 4 개 매개 변수

url

, callback, type(post in your case), 그래서 formdata

필요 게시

를 사용 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) 
} 

같은 progress 이벤트 기능을 추가 할 수 있습니다 그런 것입니다

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)) 
} 

질문이 있으시면 언제든지 문의하십시오.