【问题标题】:Ajax, failed to load PHP from serverAjax,无法从服务器加载 PHP
【发布时间】:2017-09-25 19:15:09
【问题描述】:

我正在尝试建立 PHP 连接,但我不断收到此错误。我希望有人可以提供帮助。

我的代码出现以下错误:

{
    "readyState": 0,
    "status": 0,
    "statusText": "NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://localhost/php/busca.php'."
}

我的代码是:

SendSQL.onclick = function() {

    var dataString='a=hello&b=world';

    $.ajax({
        type: "POST",
        url:"http://localhost/php/busca.php",
        data: dataString,
        async: false,
        dataType:'html',

        success: function(data){
                alert(data);
        },

        error: function(data){
            alert(JSON.stringify(data)); //Better diagnostics
        }
    });

};

而文件busca.php是:

<?php
    $a = $_POST['a'];
    $b = $_POST['b'];
    echo "$a, $b";
?>

【问题讨论】:

标签: javascript php jquery ajax html


【解决方案1】:

试试这个方法...

SendSQL.onclick = function() {

  var dataString='a=hello&b=world';

  $.ajax({
    type: "POST",
    url:"http://localhost/php/busca.php",
    data: {
      "a":"hello",
      "b":"world"
    },
    async: false,
    dataType:'text',
    success: function(data){
            alert(data);
    },
    error: function(data){
        console.log(data); 
    }
  });

};

【讨论】:

  • 谢谢,现在我可以看到错误了,它缺少一个标头 header('Access-Control-Allow-Origin: *');
【解决方案2】:

你的dataString是GET请求发送参数的方式。

让我们改成 JSON 之类的

var dataString = { "a":"hello", "b":"world" };
$.ajax({
        type: "POST",
        url:"http://localhost/php/busca.php",
        data: {data: JSON.stringify(dataString)},
        async: false,
        dataType:'json',

        success: function(data){
                alert(data);
        },

        error: function(data){
            alert(JSON.stringify(data)); //Better diagnostics
        }
    });

在php代码中,使用json_decode($_POST['data'])

【讨论】:

  • 已经解决了,问题是header少了 header('Access-Control-Allow-Origin: *');
猜你喜欢
  • 2015-08-09
  • 1970-01-01
  • 1970-01-01
  • 2012-10-13
  • 1970-01-01
  • 1970-01-01
  • 2010-11-21
  • 1970-01-01
  • 2015-07-23
相关资源
最近更新 更多