douyang5943 2015-10-06 01:53
浏览 39
已采纳

跨域ajax。 怎么检查

I am having an ajax problem. I am doing cross domain, i.e I am submitting a form on another domain.

Here is my js code:

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

and in php I am returning this string:

$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]);

I did understood from my searches that I should in my dataType use jsonp instead of json, but with jsonp I cant even submit my form.

When I submit my form with json, the data is properly inserted in my DB but I cant get any response. I tried the .success instead of .done but does not work either.

My first question, can I do cross domain with json or not.

If I need to use jsonp, how do I check in my browser that everything is going right, and how should I modify my response because right now if I use jsonp I am having an error in the console because of the ':' which seperate the key from the value.

Thanks for your help

  • 写回答

1条回答 默认 最新

  • dongnuo3749 2015-10-06 02:33
    关注

    You have set the headers also in your php in such a way that it allows you to accept request from other domains also.

    <?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]);
    
    ?>
    

    Detailed explanation is given here :
    (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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?