简体   繁体   中英

How to display data storing in ajax global variable?

The user selects one of the options and submits the form.

Then without submitting the form, I need to display data from json file.

I am storing ajax call in a global variable display_this and calling that variable as a function after form is submitted.

When I select option and press submit I get this error:

TypeError: display_this is not a function

When I refresh the page, it displays the data.

My code:

<form id="form">
  <select name="op" id="op">
    <option value="A">A</option>
    <option value="B">B</option>
  </select>
  <input value="Submit" type="submit" id="submit">
</form>

My JSON data:

[ 
  {"key":"A","val":"apple"},
  {"key":"A","val":"orange"},
  {"key":"B","val":"carrot"},
  {"key":"B","val":"onion"}
]

My jQuery code:

$(document).ready(function () {
  var output;
  var display_this = function () {
    var val = $("#op").val();

    $.ajax({
      async: 'false',
      type: 'post',
      url: 'abc.php',
      data: {
        "val": val
      },
      dataType: 'json',
      success: function (response) {
        var data = JSON.stringify(response);
        var resp = JSON.parse(data);

        $.each(resp, function (i, item) {
          if (val == "A" && resp[i].key == "A") {
            output += resp[i].val + "</br>";
          } else if (val == "B" && resp[i].key == "B") {
            output += resp[i].val + "</br>";
          }
        });
        return results.html(output);
      }
    });
  }();

  $('#form').submit(function (e) {
    e.preventDefault();
    display_this();
  });
});  

You function is not available to your form submit. I suggest this

$(function () {
  $('#form').submit(function (e) {
    e.preventDefault();
    var output;
    var val = $("#op").val();

    $.ajax({
     // async: 'false', // do NOT use async false
      type: 'post',
      url: 'abc.php',
      data: {
        "val": val
      },
      dataType: 'json',
      success: function (resp) {
        $.each(resp, function (i, item) {
          if (val == "A" && resp[i].key == "A") {
            output += resp[i].val + "</br>";
          } else if (val == "B" && resp[i].key == "B") {
            output += resp[i].val + "</br>";
          }
        });
        $("#results").html(output);
      }
    });
  });
});  

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