如何获得html返回通过javascript跨域

How to get html to return via javascript crossdomain

本文关键字:javascript 跨域 返回 何获得 html      更新时间:2023-09-26

我使用ebay,他们允许javascript。我想从我的域返回html。然而,我只知道jQuery和ebay不允许jQuery。以下是我如何在jQuery中调用该文件:

var data: {
on:1
};
var url = "myfile.php";
jQuery.post(url,data,function(response)) {
$("#element").html(response);
});
php

    <?php 
 echo "<table><tr><th>test</th></tr></table>";
    die();
    ?>

我如何在javascript中调用文件?

可以想象,用纯JavaScript发送自定义Ajax请求有点棘手。但这并不难。您不需要更改PHP文件的任何内容。但是Ajax请求的等效JavaScript代码是:

使用JavaScript的Ajax示例:
var data = { on: 1 }; // the same data parameter on your code
var xmlhttp; // the XMLHttpRequest object
if (window.XMLHttpRequest) {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp = new XMLHttpRequest();
}
else {
  // code for IE6, IE5
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// this is how you access the returned data
xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    // and bind it to your HTML
    document.getElementById("element").innerHTML = xmlhttp.responseText;
  }
}
xmlhttp.open("POST","myfile.php",true); // this prepares the Ajax call
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // sets the correct request type for POST
xmlhttp.send(data); // actually sends the request

更新:如果你得到一个关于访问控制的错误,在你的PHP文件的顶部添加这个:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');

参考:http://www.w3schools.com/ajax/default.asp

希望这能回答你的问题。