【问题标题】:Ajax code for cross-domain request fails跨域请求的ajax代码失败
【发布时间】:2013-12-29 22:01:35
【问题描述】:

我需要通过 AJAX 将数据发送到另一个域。我使用以下代码警告错误。

$(document).ready(function(){
                $('p').click(function(){    
            $.ajax({
             url:"http://tarjom.ir/demo/javascript/get.php?callback=?",
             dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
             type :  "GET",
             data: "username=mostafa&url="+window.location,
             success:function(json){
                 // do stuff with json (in this case an array)
                 alert(json);
             },
             error:function(){
                 alert("Error");
             },
            }); 
                });
    });

我希望每次点击&lt;p&gt; 标记都报告给另一台服务器上名为 get.php 的文件。该文件会将点击记录+事件时间保存到数据库中。

由于开发阶段,我在代码中添加了alert();,以提醒从 get.php 收到的任何内容,但我只会收到“错误”警报。

这里是get.php代码:

<?php
    if($_POST['username'] != "")
    {
        $site = new mysqli('localhost', 'tarjomir_mostafa', 'securefiction1916', 'demo');
        $stmt = $site->prepare("INSERT INTO demo (url) VALUES(?)");
        $stmt->bind_param('s', $a);
        $stmt->execute();
        $stmt->close();
        echo json_encode("success");
    }
?>

【问题讨论】:

  • error: function(a,b,c){ alert(c) }
  • 您提供的 URL 似乎没有返回 JSONP ......或任何东西。
  • 我已更改网址
  • 您返回的是 JSON,而不是 JSONP。修改您的 php 以返回 JSONP。

标签: javascript jquery html ajax cross-domain


【解决方案1】:

试试这个:

$(function(){

  $.ajax({
     url:"http://tarjom.ir/demo/javascript/get.php",
     dataType: 'jsonp',
     type :  "GET",
     data: "username=mostafa&url="+window.location,
     jsonpCallback:"myFunction"
  })
  .done(function(json){
         // do stuff with json (in this case an array)
         alert('done ' + json);
     })
  .fail(function(){
         alert("Error");
     });

});

http://tarjom.ir/demo/javascript/get.php 的响应类似于:

myFunction({"data": "mydata" })

【讨论】:

  • @MostafaTalebi -1???您的服务是否返回或没有返回我评论的内容?
猜你喜欢
  • 2015-01-28
  • 2014-11-22
  • 1970-01-01
  • 1970-01-01
  • 2013-08-09
  • 2023-04-01
  • 2017-12-27
  • 1970-01-01
  • 2013-03-06
相关资源
最近更新 更多