iframe AJAX请求在第一次单击时失败,之后完美无缺

时间:2011-07-18 18:27:03

标签: ajax iframe

HTML调用“ajax_request('server_code.php','result_id')”onClick。它第一次失败时出现此错误:

*未捕获TypeError:无法读取null的属性'innerHTML'ajax_request ajax.js:35(匿名函数)*

但每次后续通话都能完美运行。为什么..?

在此处下载所有文件:http://k.min.us/iejWmy.zip

HTML:

<html>
<head>
    <!-- ajax -->
    <script src='ajax.js' type='text/javascript'></script>
</head> 
    <body>
        <a id='test' href='#' onclick="ajax_request('php.php','show_result')">get ajax data</a>
        <div id='show_result'></div>
    <body>

</html>

Javascript'ajax.js'

/****************************************************************************
Iframes based AJAX function.
@ url - server side script location
@ result_id - server side script output
****************************************************************************/
function ajax_request(url,result_id)
{   
    var ajax_iframe_id = 'ajax_iframe_loader';
    var ajax_iframe = document.getElementById(ajax_iframe_id);

    // create hidden iframe transfer buffer if it's not created already.
    if (ajax_iframe == null)
    {

        var element = document.createElement("iframe");
        element.setAttribute('src',url);
        element.setAttribute('id',ajax_iframe_id);
        document.body.appendChild(element);

        element.style.display='none';
        element.style.width='1';
        element.style.height='1';
        element.style.border='0';

        ajax_iframe = element;
    }

    // load server side page into iframe buffer
    ajax_iframe.src = url;

    // get the outputted result from inside our transfer div
    var iframe_inner_doc = ajax_iframe.contentDocument || ajax_iframe.contentWindow.document;

    // target AJAX data to transfer
    var content_to_transfer = iframe_inner_doc.getElementById('to_transfer').innerHTML;

    // paste result
    document.getElementById(result_id).innerHTML = content_to_transfer;
}

PHP'php.php'

<html>
<body>
<div id='to_transfer'>random number via ajax is:<font size='15'><?=mt_rand(5, 15);?></font></div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

我看到你设置了iframe src,但没有设置AJAX。我怀疑你在iframe之前试图访问iframe的内容。一旦你加载了内容,就会存在to_transfer,但这不是第一次,因为你没有给它机会加载内部文档内容。