简体   繁体   中英

Using jQuery to assign a string echoed by PHP to a variable in Javascript

I have a MySQL database full of data that changes frequently. I need to get a string to javascript based on the contents of the MySQL database, and I've concluded that jQuery is the best way to do that. What I'd like to do is something like the following:

var myReturnedString = $.post('myphpcode.php', {myJSData}, function(data) {return data;})

The problem is that even though myphpcode.php echos a string, I think the data passed by jQuery is some kind of object, and I can't figure out how to parse it. Any suggestions?

You must specify the type of returned data.

 $.post('myphpcode.php', {myJSData}, function(data) {return data;},'dataType');

dataType could be text,json or xml

When you are calling $.post() , which is really just a wrapper for $.ajax() , you are doing two things: 1, initiating an asynchronous request to the server, and 2, setting up an event handler for when the request is completed (ie when the response is received).

This event handler works in much the same way as any other event handler, such as those setup using $.click() or $.keyDown() . So, the $.post() call completes almost instantly and the code after it continues to execute. Then, some time later, the response is received and the callback (function you pass in to $.post() ) will be fired.

So what you need is something more like:

$.post('myphpcode.php', {myJSData}, function(data) {
    // this is executed only when the request is complete.
    // the data parameter is the result of the call to the backend.
});
// code here is executed immediately after the request is fired off

PS you generally use "post" requests for sending data to the server; if you are only retrieving data, it is more common to use a "get" request, ie $.get() instead of $.post() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM