猿问

php从ajax获取变量

我正在使用 ajax 发送参数并咨询它们,只有在获取带有记录的数组不允许我独立显示值时,一切才起作用


这是 index.php


<script>

    $(document).ready(function(){

        $("#Montox").change(function(){

            var varmonto = $("#Montox").val();

            $.ajax({

                method: "post",

                url: "ajax/calc.php",

                data: {monto:varmonto}

            })

            .done(function(data){


                    $('#chattext').html(data['username1']);

                    $('#chattext2').html(data['username2']);/*I NEED TO SHOW THE DATA 'username2'*/


            });

        });

    });

</script>

这是我的 calc.php


<?php

echo json_encode(array('username1' => "luis", 'username2' => "jose"));


?>


人到中年有点甜
浏览 204回答 3
3回答

慕田峪7331174

您没有将响应解析为 JSON。你可以:使用dataType: 'json'选项$.ajax()使其自动解析为 JSON。调用header("Content-type: text/json");PHP 告诉 jQuery 响应是 JSON。data = JSON.parse(data)在.done()函数中使用以显式解析它。

HUWWW

由于您期望来自服务器的 JSON 结果,您需要dataType在 ajax 调用上设置属性以返回您可以操作的 Javascript 对象。像这样:<script>&nbsp; &nbsp; $(document).ready(function(){&nbsp; &nbsp; &nbsp; &nbsp; $("#Montox").change(function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var varmonto = $("#Montox").val();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; method: "post",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: "ajax/calc.php",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data: {monto:varmonto},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dataType: 'json'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .done(function(data){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 'data' is a javascript object, not an array!&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#chattext').html(data.username1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#chattext2').html(data.username2);/*I NEED TO SHOW THE DATA 'username2'*/&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });</script>那应该有效。

凤凰求蛊

您需要在 ajax 标头中添加 Json TYPEdataType: "json"它将允许您获取 json 文本并解析它。下一次,如果你想要真正的帮助,请发布(数据)的结果
随时随地看视频慕课网APP
我要回答