我有如下选择字段:
<select name="year" id = "year" class="dropdown-select">
<option value="2005">All Years</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
<option value="2008">2008</option>
<option value="2007">2007</option>
<option value="2006">2006</option>
</select>
我有如下jquery可以在选择新值时获取所选值:
$("#year").change(function() {
input_year = parseInt($(this).val());
});
我的问题是,每次值更改时,如何将'input_year'变量发布到PHP?
最终目标是在PHP中使用$_POST['year']进行操作,并将结果返回给JavaScript,例如echo "var res = " . $_POST['year'] . ";";。
A very simple implementation
$.ajax({
type:'POST',
url:'your_url.php',
data:'input_year='+input_year,
success: function(msg) {
console.log(msg);
}
});
data string may need a ?
before it, I can't remember off the top of my head
Use AJAX, specifically the jQuery .post()
function:
$("#year").change(function() {
input_year = parseInt($(this).val());
$.post('/path/to/file', year: input_year, function(data, textStatus, xhr) {
/*optional stuff to do after success */
});
});
$("#year").change(function() {
var input_year = parseInt($(this).val());
$.post('server.php',{year:input_year}, function(result,status){});
});
Using ajax
. With jquery
, it would be like this:
$.ajax({
type: 'POST',
dataType: 'text',
url: "(your php filename)",
data: $.param({'year': input_year}),
success:function(data){
//do whatever you need to do with the received result
}
error: function (request, status, error) {
alert(request.responseText);
}
});