javascript - 在ajax中火回两次成功

标签 javascript php html ajax

我想在ajax请求后分离结果

<input type="text" class="form-control" name="userno" id='stud_id' readonly > 
<input type="text"name="studentname" id='studentname' readonly >
<input type='submit' name='stud' onclick='showstudent_info()'>

function showstudent_info(){    
var  studid = $('#studid').val();
  console.log(studid);
    if(studid){
        $.ajax({
            type:'POST',
            url:'parentinfo.php',
            data: 'studid='+studid,
            success:function(html){
                var infoid = html
                $('#stud_id').val(info);
                var studname = html
                $('#studentname').val(studname);
            }
        }); 
    }
  } 

这是我的parentinfo.php页面

parentinfo.php
$stud_id = $_POST['studid'];
$qry = "Select studtbl.stud_id,concat(studtbl.fname,' ', 
substring(studtbl.mname, 1,1),'. ',studtbl.lname) as Name from studtbl where 
stud_id = $stud_id";
$result = mysqli_query($conn, $qry);
while($row = mysqli_fetch_array($result))
{
    extract($row);
    $info = $row['stud_id'];
    $studname = $row['Name'];
}
echo $info;
echo $studname;

我的问题是 infoid 和 Studname 的值被连接起来,例如(1Albert Einstein)

最佳答案

将其作为 JSON 发送,这样您就可以在服务器端将其分解,使其作为 javascript 对象客户端可读,而不是解析从服务器发送的字符串

在 php 中会是这样的:

$outputArray = array(
   'id'=> $idVariable,
   'name'=> $nameVariable
);

echo json_encode($outputArray);

然后在js中将dataType:'json'添加到ajax选项中,成功回调将类似于:

success:function(responseObject){
     var infoid = responseObject.id;
     $('#stud_id').val(infoid );
     var studname = responseObject.name;
     $('#studentname').val(studname);
}

关于javascript - 在ajax中火回两次成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51681484/

相关文章:

javascript - echo php 变量在backbone.js 模板中

html - 将 html 链接到 css 什么都不做(ATOM)

javascript - 如何让 Twitter 和 Facebook 按钮水平对齐?

javascript - 从李中移除子弹

javascript - 传单群控

php - PHP 中是否有一种方法可以在不使用 ob_gzhandler 的情况下从 JSON 中去除空格?

jquery - 如何更改移动应用程序中文本输入元素的大小?

javascript - JavaScript中变量的同步值

javascript - 谷歌地图 API v3 重绘?

PHPUnit:我如何模拟这个文件创建?