Ajax请求未加载,因为服务器端php文件不可用

时间:2019-06-28 21:08:11

标签: php ajax

ajax请求测试。我的问题是... test.php应该在服务器中的哪个位置才能被url:“ test.php”找到?

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>


<button type="button" onclick="create()">Click Me</button>


    <script>
    function create () {
          $.ajax({
            url:"test.php", //the page containing php script
            type: "post", //request type,
            dataType: 'json',
           data: {reg: "success", name: "bnm", email: "lolo@gmail.com"}
            success:function(result){

             console.log(result.abc);
           }
         });
     }
<script>

在服务器端的test.php文件

$regstration = $_POST['reg'];
$name= $_POST['name'];
$email= $_POST['email'];

if ($registration == "success"){
 // some action goes here under php
 echo json_encode(array("abc"=>'successfuly registered'));
}

2 个答案:

答案 0 :(得分:0)

应将其放置在与表单相同的路径中。您的代码中有错误。
试试这个

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<button type="button" onclick="create()">Click Me</button>
<script>
  function create() {
    $.ajax({
      url: "test.php", //the page containing php script
      type: "post", //request type,
      dataType: 'json',
      data: {
        reg: "success",
        name: "bnm",
        email: "lolo@gmail.com"
      },
      success: function(result) {
        console.log(result.abc);
      }
    });
  }
</script>

JSFiddle

答案 1 :(得分:0)

如果您的test.php文件与表单的路径相同,例如:

test.php

http://localhost/demo/test.php

form.html

http://localhost/demo/form.html

但是,如果您需要从其他路径对test.php文件进行请求,则需要在url中添加斜杠,然后在文件名中添加/demo/test.php