2012-08-03 112 views
2

我有了這個代碼,我看不出是哪裏的問題:發送POST方法與jQuery

if (window.XMLHttpRequest || window.ActiveXObject) { 
    var id = $(this).attr("id"); 
    alert("bon"); 
    xhr =getXMLHttpRequest(); 
    xhr.open("POST", "handlingData.php",true); 
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
    xhr.send("type="+$('input[name="type'+id+'"]').val()+"&titre="+$('input[name="titre'+id+'"]').val()+"&texte="+$('input[name="texte'+id+'"]').val()+"&reponse="+$('input[name="reponse'+id+'"]').val()); 

} 

什麼我想要做的是在一個POST發送數據。

這裏的getXMLHttpRequest():

function getXMLHttpRequest() { 
var xhr = null; 

if (window.XMLHttpRequest || window.ActiveXObject) { 
    if (window.ActiveXObject) { 
     try { 
      xhr = new ActiveXObject("Msxml2.XMLHTTP"); 
     } catch(e) { 
      xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
    } else { 
     xhr = new XMLHttpRequest(); 
    } 
} else { 
    alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest..."); 
    return null; 
} 

return xhr; 
} 
+2

爲什麼不使用jQuery的'POST'? – 2012-08-03 15:24:28

+0

我很抱歉告訴你,但這不是我做的。 – Tsunaze 2012-08-04 15:05:07

回答

3

由於您使用jQuery你可以使用$.post

// i'll show just to for example 
var data = { 
    type : $('input[name="type'+id+'"]').val(), 
    titre : $('input[name="titre'+id+'"]').val() 
} 
$.post('handlingData.php', data, function(response) { 
    // do something after the server responded 
}); 
0

爲什麼不使用jQuery post方法?你已經在使用jQuery了,不妨!

http://api.jquery.com/jQuery.post/

var data = { type: $('input[name="type'+id+'"]').val() }; // Fill this in with the data from your form. 

$.ajax({ 
    type: 'POST', 
    url: 'handlingData.php', 
    data: data, 
    success: function(data) { 
     // Do processing here... 
    } 
});