简体   繁体   English

在JS中的函数内设置变量

[英]Setting a variable inside a function in JS

   var last = 0;

   function grabProducts(searchstring) {
       var last = 0;
       $.post('ajax/products', {
           method: 'search',
           string: searchstring,
           category: $('#search_category').val(),
           sort: $('.sort').val()
       }, function (data) {
           data = $.parseJSON(data);
           $.each(data, function (index, b) {
               last = "dada";
           });
       });
   }
   alert(last);

Gives me alert with "0" . 使用"0"给我警报。 How can i make it set the variable to "dada" ? 我如何才能将变量设置为"dada"

You can't make a setup like that work because $.post() is asynchronous . 您无法进行这样的设置,因为$.post()异步的 You'll have to put the "alert" in the callback function you pass to $.post() . 您必须将“警报”放入传递给$.post()的回调函数中。

var last=0;
function grabProducts(searchstring) {
        var last=0;
        $.post('ajax/products', { method: 'search', string: searchstring, category: $('#search_category').val(), sort: $('.sort').val() }, function(data) {
            data = $.parseJSON(data);
            $.each(data, function(index, b) {
                last = "dada";

            });
            alert(last);
        });
      }

The whole point of the callback, in fact, is to provide you with a way to have code run when the HTTP request is complete. 实际上,回调的全部目的是为您提供一种在HTTP请求完成后运行代码的方式。

When you POST something, It needs time for server to respond. 当你POST的东西,它需要时间,服务器响应。 Do this: 做这个:

var last=0;
function grabProducts(searchstring) {
            var last=0;
            $.post('ajax/products', { method: 'search', string: searchstring, category: $('#search_category').val(), sort: $('.sort').val() }, function(data) {
                data = $.parseJSON(data);
                $.each(data, function(index, b) {
                    last = "dada";
                });
                    alert(last);
            });
          }

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

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