In jquery, how does ajax return values to upper-layer functions and records of js methods for processing json objects? jqueryjson
① When we do front-end js processing, we often encapsulate some common js methods to facilitate calls elsewhere. But what we need to do is to pass the value returned by the request to the caller, here I recorded how to use ajax in js to obtain background data and return it to the caller. The ajax method is usually used as follows:
<Span style = "font-family: FangSong_GB2312; font-size: 18px;"> function AutoGetOpenid () {var personJson; $. ajax ({url :"***. action ", type: 'post', ype: 'json', contentType:" application/x-www-form-urlencoded; charset = UTF-8 ", data: {'code ': location. href. split ('=') [1]. split ('&') [0]}, success: function (data) {// return the information of the user, nickname, city, openid, unionid, gender, Avatar address, etc., personJson = jQuery. parseJSON (data) ;}, error: function () {}}); return personJson ;}</span>
However, the returned personJson does not have the value we want. In fact, the reason is that ajax has two methods: Synchronous execution and asynchronous execution, ajax adopts asynchronous execution when no choice is made. Therefore, we want to modify the execution method to synchronous execution when the result is returned:
<Span style = "font-family: FangSong_GB2312; font-size: 18px;"> function AutoGetOpenid () {var personJson; $. ajax ({url :"***. action ", type: 'post', ype: 'json', contentType:" application/x-www-form-urlencoded; charset = UTF-8 ", <span style =" color: # FF0000; "> async: false, </span> data: {'code': location. href. split ('=') [1]. split ('&') [0]}, success: function (data) {// return the information of the user, nickname, city, openid, unionid, gender, profile picture address, etc.,}, error: function () {}}); return personJson ;}</span>
Looking at the red part of the code above, you only need to add this line of code to solve the problem;
② In ① We get the returned data, which is a json object of jsonobject. How can we get the value corresponding to the property?
PersonJson = jQuery. parseJSON (data );
Alert (personJson. openid );
First, let's talk about the data object, and then get the object property value through object. key!