繁体   English   中英

jQuery ajax获取对php的请求,未检索任何数据

[英]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.

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