美文网首页
JQuery的ajax()与php交互的简单例子

JQuery的ajax()与php交互的简单例子

作者: 好好他爸爸 | 来源:发表于2020-06-06 23:54 被阅读0次

index.html代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
  <!--利用cdn添加js和css库  -->
  <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
 
</head>
<body style="text-align: center; padding: 100px;">
 
 姓名: <input type="text" name="username" id="yourName" />
 
<button id="send">提交</button>
<br><br><br><br>
 
<div id="result">结果:</div>
</body>
 
<script type="text/javascript">
 
  $(function () {
      $("#send").click(function () {
 
          var name = $("#yourName").val();
          var data = "name="+name; //如果后台是$_POST方法获取数据,那么一定要索引(例如:索引name)
 
           $.ajax({
             type: "POST",
             url: "server.php",  //同目录下的php文件
             data:"name="+name,  // 等号前后不要加空格
            success: function(msg){  //请求成功后的回调函数
              
                $("#result").append("你的名字是"+msg);
 
            }
        });
 
      })
  })
 
</script>
 
</html>

server.php代码

<?php
 
    $username = $_POST['name'];//获取索引值
    echo  $username;
 
?>
image.png
image.png

多参数

ajax

$.ajax({ url: 'insert2.php',
        type: 'post',
        data:{"content":temp,"time":times}, 
        dataType:'text',
        success: function()
        {   
            alert("添加成功");
                                                                  
                    }});

php接收

$temp=$_POST['content'];
$time=$_POST['time'];

或者:

data: "name=John&location=Boston",

跨域访问

1.ajax接口数据类型:json与jsonp

1、json格式:

{
    "message":"获取成功",
    "state":"1",
    "result":{"name":"工作组1","id":1,"description":"11"}
}

2、jsonp格式:

callback({
"message":"获取成功",
"state":"1",
"result":{"name":"工作组1","id":1,"description":"11"}
})

(1)前端代码

$.ajax({
    url: 'http://www.xxx.com/xxx/server.php',
    async: false,
    dataType: 'jsonp',
    data: "name=" + name,
    jsonp: 'callback', //Jquery生成验证参数的名称
    processData: false,
    type: 'get',
    success: function(data) {
        // let a = JSON.parse(data);
        console.log(data, $.type(data));
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        // alert(XMLHttpRequest.status);
        // alert(XMLHttpRequest.readyState);
        // alert(textStatus);
        console.log(textStatus);

    }
});

2.后端

<?php

function connDb(){
    // 连接数据库.返回游标
    $odbc = "Driver={Microsoft Access Driver (*.mdb)};Dbq=".realpath("url.mdb");
    $conn = odbc_connect($odbc, '', '', SQL_CUR_USE_ODBC);
    return $conn;
}

$conn=connDb();
$sql ="select * from user";
$query = odbc_exec($conn, $sql);
$num = odbc_num_fields($query);
$callback=$_GET['callback'];
while ($row = odbc_fetch_row($query))
{
    $data= $data.'{"urse":"'.odbc_result($query,"user").'","pwd":"'.odbc_result($query,"pwd").'"},';
}
$data=substr($data, 0, -1);
echo $callback."([".$data."])";

odbc_close($con);  

?>

相关文章

网友评论

      本文标题:JQuery的ajax()与php交互的简单例子

      本文链接:https://www.haomeiwen.com/subject/indktktx.html