【问题标题】:Cross domain ajax. How to check跨域ajax。如何检查
【发布时间】:2015-10-06 10:33:17
【问题描述】:

我遇到了 ajax 问题。我正在做跨域,即我在另一个域上提交表单。

这是我的js代码:

$.ajax({
    url: $(this).attr('action'),
    type: $(this).attr('method'),
    data: $(this).serialize(),
    dataType: 'json'
})
.done(function(data) {
    console.log('what');
})
;

在 php 中我返回这个字符串:

$response = "Hmmm... Please contact the webmaster at contact@vahana.io as it seems that there is a problem with submitting this form. Error x02";
echo json_encode(['response' => $response]);

我确实从搜索中了解到,我应该在我的 dataType 中使用 jsonp 而不是 json,但是使用 jsonp 我什至无法提交我的表单。

当我使用 json 提交表单时,数据已正确插入到我的数据库中,但我无法得到任何响应。我尝试了 .success 而不是 .done 但也不起作用。

我的第一个问题,我可以用json做跨域吗?

如果我需要使用 jsonp,我如何在浏览器中检查一切是否正常,以及我应该如何修改我的响应,因为现在如果我使用 jsonp,我会在控制台中出现错误,因为 ': ' 将键与值分开。

感谢您的帮助

【问题讨论】:

标签: php jquery json ajax


【解决方案1】:

您还在 php 中设置了标头,以便您也可以接受来自其他域的请求。

<?php

  header('Access-Control-Allow-Origin: *');
  header('Access-Control-Allow-Methods: GET, POST');
  header("Access-Control-Allow-Headers: X-Requested-With");
  $response = "Hmmm... Please contact the webmaster at contact@vahana.io as it seems that there is a problem with submitting this form. Error x02";
  echo json_encode(['response' => $response]);

?>

这里给出详细解释:
(1)CORS with php headers
(2)http://www.w3.org/TR/cors/
(3)https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

【讨论】:

  • 谢谢,正在尝试弄清楚如何使其在 js 中工作,同时在 php 文件中添加标头确实解决了问题。
猜你喜欢
  • 2011-11-17
  • 2012-07-08
  • 2012-04-17
  • 2012-01-02
  • 2012-01-16
  • 2013-06-03
  • 2012-03-02
  • 2012-04-22
  • 1970-01-01
相关资源
最近更新 更多