iframe AJAX request fails on first click, works flawlessly thereafter
The HTML calls "ajax_request('server_code.php','result_id')" onClick. It fails the first time with this error:
*Uncaught TypeError: Cannot read property 'innerHTML' of null ajax_request ajax.js:35(anonymous function)*
But each subsequent call works perfectly. Why..?
Download all files here: http://k.min.us/iejWmy.zip
HTML:
<html>
<head>
<!-- ajax -->
<script src='ajax.js' type='text/javascript'></script>
<开发者_JAVA技巧;/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>
I see you set the iframe src, but no AJAX call. I suspect you're trying to access the contents of the iframe before it has any. Once you've loaded contents once, the to_transfer exists, but not the first time because you don't give it a chance to load the inner doc contents.
精彩评论