通过PHP如果阿贾克斯失败,或者加载页面 [英] Alternatively load page via php if ajax fails

查看:126
本文介绍了通过PHP如果阿贾克斯失败,或者加载页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过Ajax外部文件替换div的内容。在code我使用这样做的:

I am trying to replace the contents of a div with an external file via ajax. the code I am using to do so is :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript">
window.onload = function(){

    document.getElementById("aside").innerHTML="<img src='loadingImage.gif'>";

    var x = null;

    if (window.XMLHttpRequest) {
        var x = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        var x = new ActiveXObject('MSXML2.XMLHTTP.3.0');
    } else {
        // fallback
    }

    x.open("GET", "other_content_1.php", true);
    x.send("");
    x.onreadystatechange = function() {

        if(x.readyState == 4) {
            if(x.status==200) 
                document.getElementById("aside").innerHTML = x.responseText;
            else 
                document.getElementById("aside").innerHTML = "Error loading document";
        }
    }
} 
</script>
</head>

<body>
<div id="aside">This is other content</div>
</body>
</html>

我的问题:

如果启用JavaScript,那么上面的code工作正常,但如果JavaScript被禁用,那么PHP应加载该文件。我如何Ð做到这一点?

If JavaScript is enabled, then the above code works fine but if JavaScript is disabled, then php should load that file. How d I do this?

推荐答案

如果您打算让您的code向后没有JavaScript兼容的,那么你真的没有理由使用 AJAX 可言。如果你只是想串到你的预留元素,然后做一些事情,如:

If you are going to make your code backward compatible without JavaScript then you really have no reason to use AJAX at all. If you just want the string into your aside Element then do something like:

//first the PHP page 'other_content_1.php'
<?php
  $resp = 'Whatever String Response You Want';
?>
//now your other page
<?php
  include 'other_content_1.php';
?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
  <head>
    <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
    <title>Test</title>
  </head>
<body>
  <div id='aside'><?php echo $resp; ?></div>
  <script type='text/javascript' src='should_be_external.js'></script>
<body>
</html>

请注意,如果你想这样的事情发生,除了的onload 那么你会使用提交表单 $ _ POST $ _ GET 处理PHP的响应。

Note, that if you want this to happen besides onload then you would submit a form using $_POST or $_GET to handle the PHP response.

这篇关于通过PHP如果阿贾克斯失败,或者加载页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆