将Ajax数据发布到PHP REST SERVICE

时间:2015-03-22 09:34:17

标签: javascript php mysql json post

我知道之前已经问过这个问题,但我尝试过的解决方案都没有,我写了一个我在服务器上托管的php休息服务,我在chrome上使用了高级休息客户端数据来测试我的休息服务和它工作,它将数据发布到数据库,但当我在浏览器下面的ajax帖子中写我自己的客户端时抱怨

  

请求时没有'Access-Control-Allow-Origin'标头   资源。因此不允许来源“http://localhost:8383”   访问。

我试过在我的PHP代码中添加一个标题仍然无法正常工作我得到另一个错误...,我只是想知道我做错了什么?

 >// MY PHP REST SERVICE  
 <?php
 $servername = "localhost";
 $username = "root";
 $password = "xxxx";
 $dbname = "xxx";

 // Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
 // Check connection
 if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
 } 

 if($_SERVER['REQUEST_METHOD'] == "POST"){
 // Get data
 $name = $_POST['name'];
 $surname = $_POST['surname'];
 $email = $_POST['email'];
 $password = $_POST['password'];

 // Insert data into data base
 $sql = "INSERT INTO UserData.register (name, surname, email, password)
 VALUES  ('$name', '$surname', '$email','$password')";

  if ($conn->query($sql) === TRUE) {
  $json = array("status" => 1000, "msg" => "Done User added!");
  } else {
   $json = array("status" => 0, "msg" => "Error adding user!");
  }
 header('Content-type: application/json');
 echo json_encode($json);
 $conn->close();
 }



 > //MY java script ajax client doing the posting.

   <script type="text/javascript">        
      function RegisterUser() {

        var name = $("#name").val();
        var surname = $("#surname").val();
        var email = $("#email").val();
        var password = $("#password").val();


        $.ajax({
            type: "POST",
            url: "http://xxx.xxx.xxx.xxx/signup.php",
            data: '{"name":"' + name + '","surname":"' + surname +    '","email":"' + email + '","password":"' + password + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                alert(msg.d)
                         }

        });
  }
</script>

1 个答案:

答案 0 :(得分:0)

尝试使用.htaccess文件 Header add Access-Control-Allow-Origin "*" Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

CORS指南是here,它列出了解决CORS问题的所有可能方法。