您好我需要使用Ajax将内部URL加载到div标签中。这是我使用的代码。
function loadXMLDoc()
{
var xmlhttp;
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()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("Loading_Page").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","UserTypesPHP.php",true);
xmlhttp.send();
}
这就是我的UserTypesPHP.php的样子。
<?php
// Create connection
include('connectionPHP.php');
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Adding Student records
if (!empty($_POST['UserTypeSubmit'])){
$sqlstu1="INSERT INTO user_type(User_ID ,User_Name) VALUES('$_POST[UserTypeID]','$_POST[UserType]')";
if (!mysqli_query($con,$sqlstu1))
{
die("<script>alert( \"Error: ". mysqli_error($con)."\");window.location.href='AdminUser.php';</script>");
}
else
echo "<script>alert ('The lecture was recorded successfully');
window.location.href=' AdminUser.php';
</script>";
}
mysqli_close($con);
?>
我试图将AdminUser.php重定向到Loading_Page div。但这并不像预期的那样有效。请有人让我知道原因。
提前谢谢。
答案 0 :(得分:0)
function loadXMLDoc()
{
var xmlhttp;
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()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(xmlhttp.responseText == 'success'){
response();
}
//document.getElementById("Loading_Page").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","UserTypesPHP.php",true);
xmlhttp.send();
}
function response(){
alert ('The lecture was recorded successfully');
window.location.href=' AdminUser.php';
}
在php文件中:
<?php
// Create connection
include('connectionPHP.php');
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Adding Student records
if (!empty($_POST['UserTypeSubmit'])){
$sqlstu1="INSERT INTO user_type(User_ID ,User_Name) VALUES('$_POST[UserTypeID]','$_POST[UserType]')";
if (!mysqli_query($con,$sqlstu1))
{
die("<script>alert( \"Error: ". mysqli_error($con)."\");window.location.href='AdminUser.php';</script>");
}
else
echo "success";
}
mysqli_close($con);
?>
答案 1 :(得分:0)
这是一个简单的解决方案。它假定如果响应包含<script>
,则整个响应都是脚本 - 它不会尝试从其他HTML中解析脚本。
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
if (/<script>/.test(xmlhttp.responseText)) {
var script = document.createElement('script');
script.appendChild(document.createTextNode(xmlhttp.responseText.replace(/<\/?script.*?>/g, '')));
document.getElementByTagName("head").item(0).appendChild(script);
} else {
document.getElementById("Loading_Page").innerHTML = xmlhttp.responseText;
}
}
}