drake900918 2013-07-30 13:35
浏览 51
已采纳

使用jQuery将PHP回显的字符串分配给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?

  • 写回答

2条回答 默认 最新

  • douqiao6015 2013-07-30 14:04
    关注

    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 (i.e. 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
    

    P.S. 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, i.e. $.get() instead of $.post().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?