简体   繁体   English

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

[英]jQuery ajax get request to php not retrieving any data

I am trying to display the full name of the selected city from the dropdown in the paragraph. 我正在尝试从段落的下拉列表中显示所选城市的全名。 But the jQuery ajax call is giving no output. 但是jQuery ajax调用没有给出任何输出。

index.html 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>

learn.php 学习.php

<?php 

 switch ($_GET['state']) {
     case 'LDH' : 
     echo 'Ludhiana';
     break;
     case 'JLD' :
     echo 'Jalandhar';
     break;
     case 'CHD' :
     echo 'Chandigarh';
     break;  
 }
?> 

When the dropdown state is changed, this is supposed to print the full name of the selected city by retrieving data from the php file. 当下拉状态更改时,应该通过从php文件中检索数据来打印所选城市的全名。

Could you alert formatted url or log to console on $.get() .fail() 您能提醒格式化的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);
    });
});

You have space in your text ie in option text. 您的文本(即选项文本)中有空格。

So alway use value attribute. 因此,始终使用值属性。

Change your code to 将您的代码更改为

    <select id="states">
        <option>LDH</option>
        <option>JLD</option>
        <option>CHD</option>
    </select>

Problem is with your spaces inside the option tag. 问题出在option标签内您的空格。

you can get results by using one method from given below 2 methods 您可以使用以下两种方法中的一种来获得结果

Method 1: 方法1:

<select id="states">
<option value="LDH"> LDH </option>
<option value="JLD"> JLD </option>
<option value="CHD"> CHD </option>
</select>

and in jquery change From 并在jQuery中更改从

selectedState = $('#states option:selected').text();

to

selectedState = $('#states option:selected').val();



Method 2 方法2

use the trim() method in your PHP file 在PHP文件中使用trim()方法

switch (trim($_GET['state']))

teste fiddle is 睾丸小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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