Home  >  Article  >  Backend Development  >  Introduction to data transmission methods between php and jQuery ajax (with code)

Introduction to data transmission methods between php and jQuery ajax (with code)

不言
不言forward
2019-02-14 14:29:402222browse

This article brings you an introduction to the method of data transmission between php and jQuery ajax (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .

As a web developer, we will inevitably use ajax to submit data to the background without refreshing. The non-refresh nature of ajax greatly improves the user experience. The following is an example of interaction between php and ajax:

js code:

$.ajax({
			type: 'POST',
			url: 'file-del.php',
			data:{
				name:'test.txt'
			},
			dataType: 'json',
			success: function(data){
				if(data.code!=200){
					layer.msg('删除失败!',{icon:0,time:1000});
				}else{
					$(obj).parents("tr").remove();
					layer.msg('已删除!',{icon:1,time:1000});
				}
			},
			error:function(data) {
				console.log(data.msg);
			},
		});

php code: file-del.php

<?php
// 删除文件
$f_name=$_POST[&#39;name&#39;];
if(unlink($f_name)){
    $res=array(&#39;code&#39;=>200,&#39;name&#39;=>$f_name);
}else{
    $res=array(&#39;code&#39;=>400,&#39;name&#39;=>$f_name);
}
print_r(json_encode($res));

Due to the js code The datatype is json, so the data printed by php must also be json, otherwise ajax will not execute the success callback function, but the error callback function. So json_encode() can be used in php code, and of course we can also construct data in json format ourselves.

The above is the detailed content of Introduction to data transmission methods between php and jQuery ajax (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete