jQuery Ajax Example With JSON Response

原文链接:http://www.lennu.net/2012/06/25/jquery-ajax-example-with-json-response/


I have been lately developing a lot with Javascript in a very interesting project which is about wines. In that project we are creating a software with HTML5, Javascript, CSS and on the serverside with PHP and MySQL. I’ll post more about that project propably at fall when we release the project. It is going to be huge. This post is about some of the technologies we are using on that project.

On this project I have learned to use jQuery. It is a Javascript library to ease the development of Javascript based websites and offers massive framework for frontend web development. One major part of our project is Ajax, Asynchronous JavaScript and XML. In common language you can you can load data into website without refreshing it.

On this post I will show an example of how to do Ajax with jQuery and how to process multidimensional JSON data table coming in through Ajax.

You can test this example at http://www.lennu.net/demo/jqueryajax/.

jQuery Ajax Example with JSON Response

HTML

We will start with HTML skeleton with jQuery already embedded in it from Google.

Inside HTML we have three buttons, these buttons will be used for getting different kind of wines from our serverside.

There is also a div where the wines will appear after being fetched from serverside. Add the Javascript code below to line 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
<title>jQuery Ajax Example with JSON Response</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

<!-- Write Javascript code here -->

</head>

<body>
  <form method="post" action="">
      <button value="all" type="submit">Get All Wines!</button>
      <button value="red" type="submit">Get Red Wines!</button>
      <button value="white" type="submit">Get White Wines!</button>
  </form>
  
  <div id="wines">
  <!-- Javascript will print data in here when we have finished the page -->
  </div>

</body>
</html>

Javascript

Here we have the Javascript for the HTML.

Basically we have a submit event that fires when a button is clicked. Next we take the value of the button clicked and send it to serverside.php with jQuery’s ajax()-function. From this function we get back our JSON data which we’ll process on success.

After that it’s simple if and else to append our #wines div.

Add this to the HTML Skeleton in HEAD section.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<script type="text/javascript">
$(document).ready(function(){
  $(':submit').live('click', function() { // This event fires when a button is clicked
      var button = $(this).val();
      $.ajax({ // ajax call starts
          url: 'serverside.php', // JQuery loads serverside.php
          data: 'button=' + $(this).val(), // Send value of the clicked button
          dataType: 'json', // Choosing a JSON datatype
          success: function(data) // Variable data contains the data we get from serverside
          {
              $('#wines').html(''); // Clear #wines div
              
              if (button == 'all') { // If clicked buttons value is all, we post every wine
                  for (var i in data.red) {
                      $('#wines').append('Red wine: ' + data.red[i] + '<br/>');
                  }
                  for (var i in data.white) {
                      $('#wines').append('White wine: ' + data.white[i] + '<br/>');
                  }
              }
              else if (button == 'red') { // If clicked buttons value is red, we post only red wines
                  for (var i in data) {
                      $('#wines').append('Red wine: ' + data[i] + '<br/>');
                  }
              }
              else if (button == 'white') { // If clicked buttons value is white, we post only white wines
                  for (var i in data) {
                      $('#wines').append('White wine: ' + data[i] + '<br/>');
                  }
              }
          }
      });
      return false; // keeps the page from not refreshing 
  });
});
</script>

Serverside

Now we need the serverside where Ajax will connect, create this file by the name of serverside.php if you wish everything to run smoothly.

This simple php gets clicked buttons value sent from our Ajax-function. After that we create a multidimensional data table.

Finally we do a PHP’s JSON-encoding and if else the right table to send back to Ajax.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php

// Get value of clicked button
$button = $_GET['button'];

// Red wine table
$red = array('Chianti', 'Barolo', 'Pinot Noir');
$white = array('Chardonnay', 'Cava', 'Chablis');

// Combine red and white tables into one multidimensional table
$winetable = array(
      "red" => $red,
      "white" => $white,
);

// Finally depending on the button value, JSON encode our winetable and print it
if ($button == "red") {
  print json_encode($red);
}
else if ($button == "white") {
  print json_encode($white);
}
else {
  print json_encode($winetable);
}

?>

These codes will produce a working HTML site with jQuery doing some cool Ajax! You can use them as a skeleton when you are building your own Ajax based website.

More Javascript Coming Soon!

I hope you have learned to do Ajax with jQuery from this example and can use this example maybe for something cool and useful! I’m gonna post more Javascript themed topics in the near future, so follow my Twitter to find out about new posts.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值