2013-09-05 77 views
-1

我有點遺忘PHP,是否有更簡單的方式使用JavaScript AJAX發佈表單,不希望只添加jQuery來發布ajax請求,而沒有必須傳遞參數?使用XMLHTTPRequest/AJAX將表單發佈到PHP文件

我想通過Ajax發佈表單,而不必獲取參數並在調用中發送它們,這可能嗎?是否有下面的代碼替代...

var mypostrequest=new ajaxRequest() 
mypostrequest.onreadystatechange=function(){ 
if (mypostrequest.readyState==4){ 
    if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){ 
    document.getElementById("result").innerHTML=mypostrequest.responseText 
    } 
    else{ 
    alert("An error has occured making the request") 
    } 
} 
} 
var namevalue=encodeURIComponent(document.getElementById("name").value) 
var agevalue=encodeURIComponent(document.getElementById("age").value) 
var parameters="name="+namevalue+"&age="+agevalue 
mypostrequest.open("POST", "basicform.php", true) 
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded") 
**mypostrequest.send(parameters)** 

這是我的意圖使用POST而不是GET隱藏的是什麼的URL發送,這種感覺陌生,它是一樣使用GET。或者我看到這個錯誤?

+1

我知道你說你不不想爲此添加jQuery,但是真的值得添加jQuery,即使這樣也是如此。總之,如果不添加jQuery,沒有簡單的方法來做到這一點。 – Styphon

+0

jQuery使這容易很多 – Lance

+0

http://www.doxdesk.com/img/updates/20091116-so-large.gif從這裏:http://meta.stackexchange.com/questions/45176/when-is-使用-jquery-a-javascript-question – Pinoniq

回答

-3

只是不要使用jQuery,如果你只想要一些簡單的簡單的Ajax。

這將做的工作就好了:

// Vanilla 
var httpRequest = new XMLHttpRequest() 
httpRequest.onreadystatechange = function (data) { 
    // code 
} 
httpRequest.open('GET', url) 
httpRequest.send() 

所有榮譽都歸:https://gist.github.com/liamcurry/2597326

現在,我們還可以添加一些更多的瀏覽器支持(IE6及以上:http://caniuse.com/#search=XMLHttpRequest)@所有這些jQuery負責人:jQuery 2放棄了對IE8及更高版本的支持,因此沒有「額外的支持」。

// creates an XMLHttpRequest instance 
function createXMLHttpRequestObject() 
{ 
    // xmlHttp will store the reference to the XMLHttpRequest object 
    var xmlHttp; 
    // try to instantiate the native XMLHttpRequest object 
    try 
    { 
    // create an XMLHttpRequest object 
    xmlHttp = new XMLHttpRequest(); 
    } 
    catch(e) 
    { 
    // assume IE6 or older 
    try 
    { 
     xmlHttp = new ActiveXObject("Microsoft.XMLHttp"); 
    } 
    catch(e) { } 
    } 
    // return the created object or display an error message 
    if (!xmlHttp) 
    alert("Error creating the XMLHttpRequest object."); 
    else 
    return xmlHttp; 
} 

所有榮譽都歸:http://www.cristiandarie.ro/asp-ajax/Async.html

這個職位是由谷歌主辦的(一個非常強大的工具,你的東西輸入,它給出了答案,更多的東西)

+0

jQuery v2可能已經失去了對jQuery v1.10的支持,它仍然保留着它,並且仍然沿着v2開發。 – Styphon

+0

我認爲你錯過了這一點。我問是否有辦法做一個AJAX表單發佈,不需要我發送(參數)參數,而是像一個真正的提交按鈕,其中我所有的變量都在全局$ _POST中,我不whant跳轉到其他頁面我只是想更新同一頁面,使用GET這非常簡單,並且使用POST可以以上述方式完成,但是我正在尋找一種替代方法來使用POST來完成此操作。 – Astronaut

+0

正如m59指出的那樣,你不能在vanlilla js中做到這一點。很多框架都有一些特殊的功能來幫助您排序數據(再次參見m59)。但是,嘿,爲什麼-1?因爲我明白這個問題是錯的? – Pinoniq