如何使用jQuery和AJAX将PHP页面加载到div中?
我正在尝试编写一个函数,单击时将调用getproduct.php?id=xxx
。 我可以让innerHTML
部分出现,但是我如何调用实际完成工作的php
页面呢?
var id = id; document.getElementById("digital_download").innerHTML = "Downloading...Please be patient. The process can take a few minutes."; url = getproduct.php?id=id;
你可以用jQuery做到这一点。
var id = 1; $('#digital_download').html('Downloading...'); // Show "Downloading..." // Do an ajax request $.ajax({ url: "getproduct.php?id="+id }).done(function(data) { // data what is sent back by the php page $('#digital_download').html(data); // display data });
您可以使用以下行在div中调用或加载php页面: –
$("#content_div").load("ajax/page_url.php");
“ajax / page_url.php”是php文件的相对路径。
所以在这里你也可以用外部url替换它。
如果我错了,请分享你的知识。
编辑:原始问题没有引用jQuery。 将这个答案留在这里,其他人可能会觉得它很有用。
下面是如何使用XHR对象为没有jQuery或Prototype或其他JS库的ajax请求执行此操作。
var xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById('digital_download').innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET", 'getproduct.php?id=' + id,true); xmlhttp.send(); }
您可以通过多种方式将页面加载到分部中。
方法是
var xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById('digital_download').innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET", 'getproduct.php?id=' + id,true); xmlhttp.send(); }
这是一种没有外部参考的典型方法。
如果你参考,那么有5种方法可以使用jQuery进行ajax调用
- load():将一段html加载到容器DOM中。
- jQuery.getJSON():使用GET方法加载JSON。
- jQuery.getScript():加载JavaScript。
- jQuery.get():如果你想进行GET调用并广泛地使用响应,请使用此方法。
- jQuery.post():如果要进行POST调用并且不想将响应加载到某个容器DOM,请使用此方法。
- jQuery.ajax():如果您需要在XHR失败时执行某些操作,或者您需要动态指定ajax选项(例如cache:true),请使用此选项。
您可以使用查询来使用get或post请求
$.ajax({ type: "POST", url: url, data: data, success: success, dataType: dataType });
例
嗨您可以调用以下函数来执行此操作,它会在成功时从服务器加载数据,您也可以创建失败函数
function setValue(Id) { document.getElementById("digital_download").innerHTML = "Downloading...Please be patient. The process can take a few minutes."; var data1 = { message: Id, }; $.ajax({ data: data1, type: 'GET', url: "http://urltoscript/index.php", cache: false, dataType: "json", crossDomain: true, success: function(data) { console.log("Response for cancel is: " + data); document.getElementById("digital_download").innerHTML = data } }); }