简体   繁体   English

使用jQuery将PHP回显的字符串分配给Javascript中的变量

[英]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. 我有一个MySQL数据库,其中充满了经常更改的数据。 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. 我需要根据MySQL数据库的内容获取javascript字符串,并且得出结论,jQuery是实现此目的的最佳方法。 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. 问题是,即使myphpcode.php回显了一个字符串,我也认为jQuery传递的数据是某种对象,并且我不知道如何解析它。 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 dataType可以是text,json或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). 当您调用$.post() (实际上只是$.ajax()的包装器$.ajax() ,您在做两件事:1,向服务器发起异步请求,以及2,为事件何时设置事件处理程序。请求完成(即收到响应时)。

This event handler works in much the same way as any other event handler, such as those setup using $.click() or $.keyDown() . 此事件处理程序大致相同的方式工作的任何其他事件处理程序,如使用这些设置$.click()$.keyDown() So, the $.post() call completes almost instantly and the code after it continues to execute. 因此, $.post()调用几乎立即完成,并且代码继续执行。 Then, some time later, the response is received and the callback (function you pass in to $.post() ) will be fired. 然后,一段时间后,将收到响应,并且将触发回调(您传递给$.post()函数)。

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; PS,您通常使用“发布”请求将数据发送到服务器; if you are only retrieving data, it is more common to use a "get" request, ie $.get() instead of $.post() . 如果仅检索数据,则更常见的是使用“获取”请求,即$.get()而不是$.post()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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