Home  >  Article  >  Backend Development  >  How does js send data to php through ajax?

How does js send data to php through ajax?

尚
Original
2019-10-31 11:48:373771browse

How does js send data to php through ajax?

js sends data to php through ajax:

Recommended: php server

Use js array to complete the json object Encapsulation:

var arrX={resitems:[]};
     arrX.bookid=bookid;
     for (var i=0; i < cellList.length; i++) {
         var item=cellList[i];
          var jsonRes={};
         jsonRes.bookid=bookid;
         jsonRes.res_id=item.itemStruct.id;
         jsonRes.res_name=item.itemStruct.name;
         jsonRes.src_origin=item.itemStruct.src;
         jsonRes.src_hd=item.itemStruct.src_hd;
         jsonRes.src_sd=item.itemStruct.src_sd;
         jsonRes.src_td=item.itemStruct.src_td;
         arrX.resitems.push(jsonRes);
     };
    
     var jsonResStr=JSON.stringify(arrX);

The above code first creates the json object of arrX, and adds various attributes, variables, etc. to the object. Finally, it is converted into a string through stringify. The obtained string jsonResStr is an ordinary string and can be passed to the server through ajax.

It is worth noting that if there is Chinese here, it is no problem and there will be no garbled code problem. After completing the JOSN encapsulation, start using ajax to pass it to the PHP page.

$.ajax({
         type:"POST",
         url:"SQLHelper.php",
         dataType:"json",
         async:false,
         data:{&#39;jsonResPanel&#39;:jsonResStr},
         success:function(json){}
     });

The type of type can be GET and POST, and the url is a script program processed by the server. The dataType types include text, json, xml, etc., async usually uses false, data is the specific json string to be passed, and posts a data called json field to the server, which can be obtained by $_POST['json'] on the PHP side Posted data. Receive return data if needed.

The above is the detailed content of How does js send data to php through ajax?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:How to use js with phpNext article:How to use js with php