Home > Web Front-end > JS Tutorial > Implementation method of passing json data with php+jquery

Implementation method of passing json data with php+jquery

php中世界最好的语言
Release: 2018-04-26 14:45:22
Original
2465 people have browsed it

This time I will bring you the implementation method of php jquery passing json data. What are the precautions for php jquery passing json data? The following is a practical case, let's take a look.

html page:

<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
 $(function(){
   $("#send").click(function(){
    var cont = $("input").serialize();
    $.ajax({
      url:'ab.php',
      type:'post',
      dataType:'json',
      data:cont,
      success:function(data){
       var str = data.username + data.age + data.job;
       $("#result").html(str);
    }
  });
 });
 });
</script>
</head>
<body>
<p id="result">一会看显示结果</p>
<form id="my" action="" method="post">
 <p><span>姓名:</span> <input type="text" name="username" /></p>
 <p><span>年龄:</span><input type="text" name="age" /></p>
 <p><span>工作:</span><input type="text" name="job" /></p>
</form>
<button id="send">提交</button>
</body>
</html>
Copy after login
php page:

<?php
header("Content-type:text/html;charset=utf-8");
    $username = $_POST[&#39;username&#39;];
    $age = $_POST[&#39;age&#39;];
    $job = $_POST[&#39;job&#39;];
    $json_arr = array("username"=>$username,"age"=>$age,"job"=>$job);
    $json_obj = json_encode($json_arr);
    echo $json_obj;
?>
Copy after login
Use post method

<script type="text/javascript">
 $(function(){
 $("#send").click(function(){
   var cont = {username:$("input")[0].value,age:$("input")[1].value,job:$("input")[2].value};
   var url = 'ab.php';
   $.post(url,cont,function(data){
    var res = eval("(" + data + ")");//转为Object对象
   var str = res.username + res.age + res.job;
  $("#result").html(str);
  });
 });
 });
</script>
Copy after login
I believe you have mastered the method after reading the case in this article, and there will be more exciting things Please pay attention to other related articles on php Chinese website!

Recommended reading:

AJAX uses proxy, JSONP, and XHR2 to achieve cross-domain

##JS encapsulates the same domain, jsonp cross-domain Domain (with code)

The above is the detailed content of Implementation method of passing json data with php+jquery. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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