简体   繁体   English

append div 到网页 - 使用 ajax 发布数据

[英]append div to webpage - using ajax to post data

The user selects a state from a drop-down field, then ajax posts that value to the database, to retrieve a list of high schools located within that state.用户从下拉字段中选择 state,然后 ajax 将该值提交到数据库,以检索位于该 state 内的高中列表。

I also have other fields asking for their name and email address.我还有其他字段询问他们的姓名和 email 地址。 Once the user selects the state, it retrieves the appropriate high schools and displays a new drop-down with those high schools, and here is where I am having a problem, it duplicates the other fields: name and email.用户选择 state 后,它会检索相应的高中并显示包含这些高中的新下拉列表,这就是我遇到问题的地方,它复制了其他字段:名称和 email。

html html

<form>
<div id="inquiry-form">
  name:
  email:
  state drop-down field
</div>

<div id="high-schools">
  high school drop-down field
</div>

submit button
</form>

js js

$(document).ready(function() {

  $('#state').bind('change', function() {
    var form_data = {
      state : $('#state').val(),
      ajax : '1'
    };

    $.ajax({
      url: '/recruiter-card/index.php/inquiry/index',
      type: "POST",
      data: form_data,
      success: function(msg) {
        $("#high-schools").html(msg);
      }
    });
    return false;
  });

});

I don't have a jsfiddle for this, here is a screenshot of what it does after selecting a state, it duplicates all the fields.我没有用于此的 jsfiddle,这是它在选择 state 后执行的操作的屏幕截图,它复制了所有字段。

在此处输入图像描述

What is the best way of displaying the high school drop-down and keeping all the other fields intact, without duplicating?显示高中下拉列表并保持所有其他字段完整而不重复的最佳方式是什么?

I suspect, that the ajax return contains more than only the select. Try following:我怀疑 ajax 返回包含的不仅仅是 select。请尝试以下操作:

...
  success: function(msg) {
    $("#high-schools").html($(msg).find('#high-schools').html());
  }
});
...

Also see this example .另请参阅此示例

There are a couple of ways you can fix this.有几种方法可以解决此问题。 First, you could simply change the backend code to only return the portions of the form that you do not send data for.首先,您可以简单地更改后端代码以仅返回您不为其发送数据的表单部分。 So if you send a state, only return the field(s) after state. You could also make this dependent on an extra parameter, such as ajax=1 , so you can use this same backend script multiple ways.因此,如果您发送 state,则只返回 state 之后的字段。您也可以使它依赖于一个额外的参数,例如ajax=1 ,这样您就可以通过多种方式使用同一个后端脚本。

The other way is to use jQuery to strip out the parts of the field you want/don't want:另一种方法是使用 jQuery 去除您想要/不想要的字段部分:

$(document).ready(function() {

  $('#state').bind('change', function() {
    var form_data = {
      state : $('#state').val(),
      ajax : '1'
    };

    $.ajax({
      url: '/recruiter-card/index.php/inquiry/index',
      type: "POST",
      data: form_data,
      success: function(msg) {
        $("#high-schools").html($(msg).filter("#high-schools").html());
      }
    });
    return false;
  });

});

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

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