利用ajax执行php并且传递参数

web前端 专栏收录该内容
2 篇文章 0 订阅

第一种:不需要引用jquery库

<script type="text/javascript">
        window.onload=function(){
		var xmlhttp;
		if (window.XMLHttpRequest)
		  {// code for IE7+, Firefox, Chrome, Opera, Safari
		     xmlhttp=new XMLHttpRequest();
		  }
		else
		  {// code for IE6, IE5
		     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		  }
        xmlhttp.onreadystatechange=function ff()
         {
           if (xmlhttp.readyState==4 && xmlhttp.status==200)
           {
      
             var xmlDoc = xmlhttp.responseXML; 
              //这里把返回的数据以XML的格式存到变量中。
             //还有一种返回式以字符串的形式返回,responseText,这个可以用下标法逐个输出,但是注意,逐个输出的是字符,
             //也就是说,你想要的一个字符串会被拆成几份
              
             //这里的 getElementsByTagName("time")[0].childNodes[0].nodeValue; 是采用遍历数的方法逐个输出数据
               //getElementsByTagName 是通有的("  ")这里写的是你链接的文件里面的标签名,等下介绍再详说,[0]也是要写的
             //.childNodes[0].nodeValue;  这块也是通有的,意思是获取值
             var number = xmlDoc.getElementsByTagName("number")[0].childNodes[0].nodeValue;
             //var number1 = xmlDoc.getElementsByTagName("number1")[0].childNodes[0].nodeValue;
            //进行插入
             var uu=document.getElementById("u");
		     var time=new Date();
		    // alert(order1);
		        //var times=order[number]['time'];
		     for (var i=0;i<number;i++)
		        {   
		        	var temp=xmlDoc.getElementsByTagName("content")[i].childNodes[0].nodeValue;
		        	var times=xmlDoc.getElementsByTagName("time")[i].childNodes[0].nodeValue;
			        //var times=time.getFullYear()+"-"+(time.getMonth()+1)+"-"+time.getDate()+" "+time.getHours()+":"+time.getMinutes()+":"+time.getSeconds();
				    var li=document.createElement("li");
				    li.innerHTML="<p>"+temp+"</p>\<br>\<br>\<font style=\"size: 2px;color: #999\">"+times+"\</font> &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp  &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp  <button  type=\"button\" onclick=\"delete1(this)\"  style=\"background: transparent; opacity:0.5  ; background:rgba(255, 251, 240, 0);border-width:0px; \"margin-left:5px; >删除</button>";
				    uu.prepend(li); 
			    }
            }
         }
	xmlhttp.open("GET","selMood.php",true);
	xmlhttp.send();
}
</script>

open()里面的参数分别传输的方式,这里是GET,,因此待会的PHP里面会采取GET方式获取传递的参数。PHP的地址链接,是否为异步模式,true为异步,这里需要注意下,如果是异步则ajax函数里的变量不能给全局变量赋值。

  如果满足xmlhttp.readyState==4 && xmlhttp.status==200这个条件则会执行里面的函数,注意这里用ajax时,界面是不会跳转的,只会转到相应执行界面里完成操作后就会返回到当前界面,一般用于前端与数据库的交互。

在里面的函数里var number = xmlDoc.getElementsByTagName("number")[0].childNodes[0].nodeValue;用这个可以获取相应标签里的值,如果有多个这个标签,则更改第二个下标的值可以获取第几个标签的值。
 

这里的selMood.php:

<?php
header('Content-Type: text/xml');
header("Cache-Control: no-cache, must-revalidate");

$servername ="localhost";
$username = "root";
$password = "123456";
// 创建连接
$conn = mysqli_connect($servername, $username, $password);
// 检测连接
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$res=mysqli_select_db($conn,"personpage");
if ($res==0)
echo "选择数据库出错";

$tt="SELECT * FROM mood";

//$sql = "SELECT content FROM blog where lookNum=43";
$result1=mysqli_query($conn,$tt);

if($result1==0)
 {
  printf("Error: %s\n", mysqli_error($conn));
  exit();
}
$number=0;
$number1=24;
$order=array(array("12","sd"),array("sd","sd"));
$order1=array("12","sd","sd");
echo '<?xml version="1.0" encoding="ISO-8859-1"?><person>';
while($row=mysqli_fetch_array($result1))
   {
       
       echo "<content>".$row['content']."</content>";
       echo "<time>".$row['time']."</time>";
       //echo "<br>";
       $number++;
       //echo "<br>";
       //header("location:url地址");
   }
   //echo $order[0][0].$order[0][1];
   //echo $order[1][0].$order[1][1];
   //print_r(json_encode( $order))
   echo "<number>".$number."</number>" ;
   echo "</person>";
  ?>

执行了一个查询操作,这里为了把数据库的值传递到之前的前端页面中,用echo并加标签界定,方便在前端的ajax中取出。

在这里有一个循环,所以会有数个<content>和<time>标签,但是不影响我们使用。还有一个<number>标签,<person>标签没用。

  第二种:直接用到jQuery的库函数

<script type="text/javascript">
			function myfunction1()
{
    var temp=document.getElementById("t").value;
    var time=new Date();
    var times=time.getFullYear()+"-"+(time.getMonth()+1)+"-"+time.getDate()+" "+time.getHours()+":"+time.getMinutes()+":"+time.getSeconds();
    var uu=document.getElementById("u");
    var li=document.createElement("li");
    li.innerHTML="<p>"+temp+"</p>\<br>\<br>\<font style=\"size: 2px;color: #999\">"+times+"\</font> &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp  &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp <button type=\"button\" onclick=\" delete1(this)\" style=\"background: transparent; opacity:0.5  ; background:rgba(255, 251, 240, 0);border-width:0px; \"margin-left:5px; >删除</button>";
    uu.prepend(li); 
	//window.location.href="insert2.php?content="+temp;
	$.ajax({ url: 'insert2.php',
		type: 'post',
		data:{"content":temp,"time":times}, 
		dataType:'text',
		success: function()
		{	
			alert("添加成功");
																  
					}});
}
	
		</script>

用了$.ajax调用,其中的URL是php地址,type是传输类型,传输的数据放到data中,并用字符串标签标示,数据类型普通的可以直接用text,success里面的函数是返回成功执行的函数。

这里的insert2.php:

<?php 
$servername = "localhost"; 
$username = "root"; 
$password = "123456"; 
$dbname = "personpage"; 

// 创建连接 
$conn = new mysqli($servername, $username, $password, $dbname); 
// 检测连接 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 

$temp=$_POST['content'];
$time=$_POST['time'];
//$time='2016-03-23 23:12:23';
$sql = "INSERT INTO mood (content, time) 
VALUES ('".$temp."','".$time."')"; 

if ($conn->query($sql) === TRUE) { 
    echo "New record created successfully"; 
} else { 
    echo "Error: " . $sql . "<br>" . $conn->error; 
} 

$conn->close(); 
?>

在PHP里即可用$_POST['标签名']这样来获取ajax传递过来的参数,然后完成相应的操作就好了。

  • 2
    点赞
  • 0
    评论
  • 5
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 点我我会动 设计师:白松林 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值