跨域请求的Ajax代码失败

时间:2013-09-19 15:47:58

标签: javascript jquery html ajax cross-domain

我需要通过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");
             },
            }); 
                });
    });

我希望每次点击<p>标记都报告给另一台服务器上名为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");
    }
?>

1 个答案:

答案 0 :(得分:-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" })