Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

javascript - Ajax call to PHP is returning nothing

I'm trying to make my first ajax example working on my MAMP. my ajax.html looks like:

<html>
<head>
<script src='ajax.js'></script>
</head>
<body onload = 'ajax()'>
<div id='test'></div>
</body>
</html>

my ajax.js looks like:


function ajax()
{
>>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.open("GET","http://localhost:8888/ajax.php",true); xmlhttp.send(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("test").innerHTML=xmlhttp.responseText; } } }

my ajax.php looks like:

echo 'hello world';

I detected response header from firebug:

Response Headers
Connection Keep-Alive
Content-Length 11
Content-Type text/html
Date Mon, 05 Nov 2012 18:57:46 GMT
Keep-Alive timeout=5, max=99
Server Apache/2.2.22 (Unix) mod_ssl/2.2.22 OpenSSL/0.9.8r DAV/2 PHP/5.4.4
X-Pad avoid browser bug
X-Powered-By PHP/5.4.4

but nothing in response text and nothing changed in my html.

Anyone could help me out please?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem is that you're trying to do a cross domain request. The browser prevents it due to same origin policy.

The standard solution is to set CORS headers in your PHP to allow those requests.

For example :

<?php
header("Access-Control-Allow-Origin: *");
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...