javascript - 如何通过javascript跨域返回html

标签 javascript cross-domain

我正在使用 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

希望能回答您的问题。

关于javascript - 如何通过javascript跨域返回html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31428688/

相关文章:

jquery - Internet Explorer中跨域POST请求ajax

javascript - 检测页面是否在 iframe 内并获取 iframe id

javascript - 如何在 JSON.stringify 中保留数字字段

javascript - 尝试读取 csv 数据时未捕获语法错误

javascript - Tomcat 5.5 的跨源资源共享

cookies - AngularDart 的Cors问题-未设置Cookie

javascript - 来自表单提交的数据无法插入数据库行

javascript - 全宽响应图像重叠 Bootstrap 3

javascript - GSAP-reverse() 不动画回来

javascript - 循环多维数组