我有点忘记PHP,有没有更简单的方法使用JavaScript AJAX发布表单,不想添加jQuery只是为了发布ajax请求,而不必传递参数?
我想通过 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 相同。还是我看错了?
如果你只想要一些简单的Ajax,就不要使用jQuery。
这将很好地完成工作:
// 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
这篇文章是由谷歌赞助的(一个非常强大的工具,你输入东西,它会提供更多带有答案的东西)