2017-09-25 70 views
0

我试图做一个PHP连接,但我不断收到此错误。我希望有人能帮忙。Ajax,未能从服务器加载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"; 
?> 
+0

是什么SendSQL? – epascarello

+3

可能重复的[NetworkError:无法执行'XMLHttpRequest'发送'](https://stackoverflow.com/questions/32878613/networkerror-failed-to-execute-send-on-xmlhttprequest) – aynber

+0

在javascritp它是var SendSQL = document.getElementById('SendSQL');但是在html上是一个按钮:

回答

0

试试这个办法...

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); 
    } 
    }); 

}; 
+0

谢谢你,现在我可以看到错误,它缺少一个头文件头('Access-Control-Allow-Origin:*'); –

0

您的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'])

+0

我试了一下,没有什么改变 –

+0

我编辑了我的答案,请尝试一下:) – HoangNK

+0

已经解决了,问题是头部丢失头('Access-Control-Allow-Origin:*'); –