跨域请求的 Ajax 代码失败

Ajax code for cross-domain request fails

本文关键字:代码 失败 Ajax 请求      更新时间:2023-09-26

我需要通过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收到的任何内容,但我只收到警报"错误"。

这是获取.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");
    }
?>

试试这个:

$(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" })