[英]jQuery ajax get request to php not retrieving any data
我正在嘗試從段落的下拉列表中顯示所選城市的全名。 但是jQuery ajax調用沒有給出任何輸出。
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Learn Javascript</title>
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<select id="states">
<option> LDH </option>
<option> JLD </option>
<option> CHD </option>
</select>
<br/>
<p>The Full name is: <span id="fullname"></span></p>
<script>
$(document).ready(function() {
$('#states').change(function() {
selectedState = $('#states option:selected').text();
$.get('learn.php?state='+selectedState, function(data) {
$('#fullname').html(data);
});
});
});
</script>
</body>
</html>
學習.php
<?php
switch ($_GET['state']) {
case 'LDH' :
echo 'Ludhiana';
break;
case 'JLD' :
echo 'Jalandhar';
break;
case 'CHD' :
echo 'Chandigarh';
break;
}
?>
當下拉狀態更改時,應該通過從php文件中檢索數據來打印所選城市的全名。
您能提醒格式化的URL還是登錄$.get() .fail()
控制台
$('#states').change(function() {
selectedState = $(this).val();
url = 'learn.php?state=' + selectedState;
alert(url);
$.get(url, function(data) {
$('#fullname').text(data);
})
.fail(function(xhr, status, error) {
console.log(xhr.status);
console.log(error);
});
});
您的文本(即選項文本)中有空格。
因此,始終使用值屬性。
將您的代碼更改為
<select id="states">
<option>LDH</option>
<option>JLD</option>
<option>CHD</option>
</select>
問題出在option標簽內您的空格。
您可以使用以下兩種方法中的一種來獲得結果
方法1:
<select id="states">
<option value="LDH"> LDH </option>
<option value="JLD"> JLD </option>
<option value="CHD"> CHD </option>
</select>
並在jQuery中更改從
selectedState = $('#states option:selected').text();
至
selectedState = $('#states option:selected').val();
方法2
在PHP文件中使用trim()方法
switch (trim($_GET['state']))
睾丸小提琴是
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.