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

不言
Release: 2023-04-05 08:14:02
forward
2249 people have browsed it

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);
			},
		});
Copy after login

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));
Copy after login

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!

Related labels:
php
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template