【问题标题】:How to call part of a form by Ajax?如何通过 Ajax 调用表单的一部分?
【发布时间】:2011-10-21 16:05:31
【问题描述】:

我有一个包含很多盒子的表格。我想添加一个复选框字段,因为值来自通过 Ajax 调用的 php 文件。如何在另一个表单中处理一个表单?

<form action="result.php" method="post">
<input ...

-------Inner form (imaginary form to perform Ajax call)
TYPE YOUR COUNTRY AND POPULATE CITY
(here user types a country and we populate cities from city.php?q=typed-country. 
City will return by the output of city.php file. In other words, output of 
city.php is exactly list of cities, which can be formatted with required 
CHECKBOX codes)
List of cities as CHECKBOX; e.g.
<input type="checkbox" name="city" value="city1" />
<input type="checkbox" name="city" value="city2" />
<input type="checkbox" name="city" value="city3" />
--------

<input type="submit" value="Submit" />
</form>

有两个选择字段用于捕获所选国家/地区的城市的示例;但在这里我需要国家的类型输入和结果城市的复选框。

【问题讨论】:

  • 你必须告诉我们你是如何返回城市列表的。给出一个示例输出。另外,我认为您的意思是 city.php?q=typed-country
  • @Amaan 你是对的错字。 php部分不是我的问题,我可以用任何需要的方式处理它;我的问题与javascript部分有关。我进一步举例。
  • 我不太明白最后一句话。您使用选择元素获取国家/地区,并希望使用复选框向用户显示返回的城市。那是对的吗?正如 Derek 所说,您的 HTML 似乎是错误的。你不能有一个“内在形式”。由于您使用的是 AJAX,因此您不需要内部表单。
  • 无选择!用户输入国家(文本输入表单),城市列表将作为复选框列表提供给他们。
  • 好的。我已经回答了您的问题,假设您将返回用逗号分隔的城市,并且您有一个 ID 为 cityListContainer 的 div,您希望在其中显示您的复选框。

标签: php javascript html ajax forms


【解决方案1】:
var ajax = new XMLHttpRequest();
ajax.open('GET','cities.php?q='+document.getElementById('country').value,true);
ajax.send();
citiesList = new Array();
ajax.onreadystatechange = function(){
    if(ajax.readyState == 4){
        citiesList = ajax.responseText.split(',');
    }
}
for(var i=0;i<citiesList.length;i++){
document.getElementById('citiesListContainer').innerHTML+='<input type="checkbox" value="'+citiesList[i]+'" /> '+citiesList[i]+'<br>';
}

使用上面的代码,您的查询将返回城市列表,每个城市用逗号分隔。在您的 HTML 中,您有一个 div,其 id 为 cityListContainer。 您也可以使用 appendChild 方法添加每个单独的复选框,但我的是懒人的答案。 Demo

【讨论】:

    【解决方案2】:

    表单中不能有表单。您可以提交整个表单(仅使用必要的数据)或将两个表单分开。

    【讨论】:

    • 不,它只是在解释问题。因为我不能在另一个表单中包含一个表单,所以我问我如何在我的表单中提供一个来自 Ajax 调用的复选框列表。
    【解决方案3】:

    在国家/地区使用 .change

    $("#country").change(function () {    
        $("select option:selected").each(function () {        
            var value = $(this).value()
            ajax to your php, return info you need
                modify/build your city information
        });    
    })
    

    这将是一个选择框的例子,但是使用 .change 的原则对于任何类型都是相同的,尽管您不需要选择选项:selected.each 位

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-27
      • 2018-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      • 2018-01-12
      相关资源
      最近更新 更多