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 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏