如何通过表单操作传递下一页中的js变量

时间:2016-12-12 06:45:35

标签: php jquery twitter-bootstrap

这里我写了一个ochnage函数,功能正常,现在问题var city_id 我想通过home.php,怎么办呢?在home.php页面我想要城市ID和城市名称



$('.options').on('change', function() {
     var city_id = $('#options option[value="' + $('#location12').val() + '"]').data('id');
		 alert(city_id);
		
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form method="POST" action="home.php">
<input list="options" type="name" class="form-control options" style="border-radius:0px;height: 36px;" name="location12" id="location12" placeholder="City" >
	<datalist id="options">
	<option data-id="1" value="Bangalore"></option>
	<option data-id="2" value="Chennai"></option>
	<option data-id="3" value="Karur"></option>
</datalist>
<input type="submit" value="submit">
</form>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

您可以尝试添加隐藏的输入字段并将city_id设置为它并使用表单

传递

$('.options').on('change', function() {
     var city_id = $('#options option[value="' + $('#location12').val() + '"]').data('id');
		$('#city_id').val(city_id);
		
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form method="POST" action="home.php">
<input list="options" type="name" class="form-control options" style="border-radius:0px;height: 36px;" name="location12" id="location12" placeholder="City" >
	<datalist id="options">
	<option data-id="1" value="Bangalore"></option>
	<option data-id="2" value="Chennai"></option>
	<option data-id="3" value="Karur"></option>
</datalist>
<input type="hidden" name="city_id" id="city_id">
<input type="submit" value="submit">
</form>

答案 1 :(得分:0)

您可以在查询字符串中传递此内容,如:

$('.options').on('change', function() {
     var city_id = $('#options option[value="' + $('#location12').val() + '"]').data('id');

var url = 'home.php?city=' + city_id;
window.location.href = url;
// This will redirect user to **home.php** with selected city.
});

在home.php上,您可以使用以下方式获取此值:

$_GET['city'];

答案 2 :(得分:0)

试试吧......

Javascript

 $('.options').on('change', function() {
         var city_id = $('#options option[value="' + $('#location12').val() + '"]').data('id');
             $("#form").attr('action','home.php?city_id='+city_id);
             $("#submit").click();

    });

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form method="POST" action="" id="form">
<input list="options" type="name" class="form-control options" style="border-radius:0px;height: 36px;" name="location12" id="location12" placeholder="City" >
    <datalist id="options">
    <option data-id="1" value="1">Bangalore</option>
    <option data-id="2" value="2">Chennai</option>
    <option data-id="3" value="3">Karur</option>
</datalist>
<input type="submit" value="submit" id="submit">
</form>