我正在尝试从另一个域 (HTTPS) 上托管的 PHP 脚本写入输出。
这是我的 PHP 文件:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
echo "lol";
这是我的 HTML 代码(在另一个域上):
<script>
var data_from_ajax;
$.get('LINK/script.php', function(data) {
data_from_ajax = data;
});
document.write(data_from_ajax);
</script>
后面的目标是传回 URL 变量,然后产生不同的输出。
但是,目前 - document.write
返回“未定义
”。
最佳答案
你得到“未定义”,因为“document.write”在回调之前被调用。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<!-- Script at the end -->
<script type="text/javascript" >
var data_from_ajax = "";
$.get('script.php', function(response) {
// This function is called when script.php has responded.
data_from_ajax = data;
document.open();
document.write(data);
document.close();
});
</script>
</body>
</html>
关于javascript - JQUERY AJAX GET - CORS header PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30707749/