没有html表单的Ajax POST请求和纯JS

时间:2016-04-19 12:53:37

标签: javascript php ajax

是否可以在没有HTML表单的情况下制作ajax帖子?如果它是我应该怎么做以及用什么PHP变量来获取变量? PHP位于获取的文件中。我没有使用任何框架。



function ajax(instruction, push, url, callback){
	
	var xmlhttp; // the object for the httprequest
	
	if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
		
		
		
		
        xmlhttp.onreadystatechange = function() { // every time the readystate changes
		   
		   
            ajaxLoad(xmlhttp.readyState); // Calls function with the ready state each time it uppdates
		   

            if (xmlhttp.readyState == 4) { // status 200 = sucessfull page! NOT 404!  // 1 2 3 4 are states of the request (4 is when it's done)
			
		        // When load bar is complete
		
		
		
		
		        if(xmlhttp.status == 200){
					
				    callback(xmlhttp.responseText); // goes to the callback function (from the argument "callback") and then passes the xmlhttp
					
				}
		        else if(xmlhttp.status == 404){ // Could not find file
           		
					ajaxError() // Function that will call the ajax but with the error file
				
				}else{}
			    
				ajaxDone(); // activates all the nessesary js to check what to do with some parts of the site
            }
			else{}
			
        };
		
	
        xmlhttp.open(instruction,url, true); // sends a the var q to the next php file
        
		if(instruction === "GET"){
		    xmlhttp.send('');             // Sends the request
		}
		else if(instruction === "POST"){
			
			xmlhttp.send(url);             // Sends the request
			
		}
		else{
			console.log("This ajax does not support " + instruction + " requests.");
		}
	
	
	
	
	
	if(push == true){ // Change the link to the url of the ajax with

		var urlPath = window.location.protocol + "//" + window.location.host + window.location.pathname; // where the host is on
		
		
		if(url == "home.php"){ // If it's the starting page REMOVE THE ?p= !!
           
 		    var urlPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
            window.history.pushState({path:urlPath},'','./'); // an empty url push	(!REMOVE THE DOT WHEN THE SITE IS HOSTED PROPERLY)		
		    return; // exit's the function
		
		}else{}
		
		
        var newLink = "?p=" + url; // Gives us the link we want except that we don't want the .php
        newLink = newLink.substring(0, newLink.indexOf('.')); // makes a new string with character 0 to the dot! Will not include the ending of the file

           
		window.history.pushState({path:urlPath},'',newLink); // the push
		
    }	
    else{}
	
}

<a href="?p=page1" onclick="ajax('POST', true, 'page1.php', function(content){ document.getElementById('content_holder').innerHTML = content;});  return false;">To page 1</a>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

你可以在这里找到一些关于如何制作Vanilla JS Ajax调用的答案: http://www.sitepoint.com/guide-vanilla-ajax-without-jquery

即将发送没有表格,您已在此处获得回复: Send POST data using XMLHttpRequest

你可以使用全局变量$ _GET [&#34; your_param_name&#34;]和$ _POST [&#34; your_param_name&#34;]获取你的params服务器端(php),它们是数组,所以我认为你知道如何使用它们。

答案 1 :(得分:1)

当然,您可以在纯js中创建AJAX请求,甚至jquery在后面的纯js中处理ajax请求。

<强> JavaScript的:

var ajax = {};
ajax.x = function () {
    var xhr;

    if (window.XMLHttpRequest) {

        xhr = new XMLHttpRequest();
    } else {

        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xhr;
};

ajax.send = function (url, callback, method, data, async) {
    if (async === undefined) {
        async = true;
    }
    var x = ajax.x();
    x.open(method, url, async);
    x.onreadystatechange = function () {
        if (x.readyState == 4) {
            callback(x.responseText)
        }
    };
    if (method == 'POST') {
        x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    }
    x.send(data)
};

ajax.get = function (url, data, callback, async) {
    var query = [];
    for (var key in data) {
        query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
    }
    ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async)
};

ajax.post = function (url, data, callback, async) {
    var query = [];
    for (var key in data) {
        query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
    }
    ajax.send(url, callback, 'POST', query.join('&'), async)
};

调用Ajax方法: 我建议您不要在onclick中使用它。

ajax.get('ajax.php',{DATA_TO_PASS},function(response) {
   //Do something with response 
   console.log(response);
},true);

$_GET接收ajax数据; OR:

ajax.post('ajax.php',{DATA_TO_PASS},function(response) {
   //Do something with response 
   console.log(response);
},true);

$_PSOT接收ajax数据;

答案 2 :(得分:0)

您不需要表格来使用ajax帖子。

$.post( "test.php", { 'choices[]': [ "Jon", "Susan" ] } );

与使用表单的方式相同,您可以使用$ _POST

从php中获取值