如何从ajax的数据成功中选择结果?

时间:2016-09-08 01:41:52

标签: php jquery ajax codeigniter

这些是我的代码:

$("#promo_form").submit(function(stay){
    $.ajax ({
        type: "post",
        url: "<?=base_url()?>promo/code_validate",
        data: $("#promo_form").serialize(),
        success: function(data){
            $("#myModalLabel").html(data);
        }
    });
    stay.preventDefault();
});

成功数据结果如下:

  

$ result1 =“代码无效”;

     

$ result2 =“promo unavailable”;

如何选择并检索它?

这是我在下面做的,但现在正在工作。

$("#myModalLabel").html(data->result1);

4 个答案:

答案 0 :(得分:1)

JavaScript使用点语法来访问对象属性,所以......

$("#myModalLabel").html(data.result1);

我还要补充一点,您要确保promo/code_validate处的页面打印出JSON响应,因为这就是data将成为对象的方式({{1}关于如何解析服务器的响应是明智的,请参阅下面的链接)。因此,您的$.ajax页面可能如下所示:

code_validate

http://api.jquery.com/jquery.ajax/

答案 1 :(得分:0)

Vincent,将dataType参数添加到您的ajax调用中,将其设置为“json”。然后只需解析响应以将其转换为对象,以便您可以轻松访问变量,例如

in AJAX call:
dataType: "json"

in success function:
var obj = jquery.parseJSON(data);
console.log(obj);//echo the object to the console
console.log(obj.result1);//echo the result1 property only, for example

答案 2 :(得分:0)

执行所需操作的最简单方法是创建值的php关联数组,然后json对数组进行编码并回显结果字符串,如下所示:

$response = ["result1"=>"code is invalid", "result2"=>"promo unavailable"];
echo json_encode($response);

然后在客户端,像这样访问它们

$("#promo_form").submit(function(stay){
    $.ajax ({
        type: "post",
        url: "<?=base_url()?>promo/code_validate",
        data: $("#promo_form").serialize(),
        success: function(data){
           $("#modal-1").html(data.result1); 
           $("#modal-2").html(data.result2);
        }
    });
    stay.preventDefault();
});

答案 3 :(得分:0)

这样做

功能控制器

function code_validate()
{
    echo json_encode(array('result1'=>'Code is invalid',
                           'result2'=>'Promo not available');
}

<强>的Javascript

$("#promo_form").submit(function(stay){
    $.ajax ({
        type: "post",
        url: "<?=base_url()?>promo/code_validate",
        data: $("#promo_form").serialize(),
        success: function(data){
            var mydata = JSON.parse(data);
            console.log(mydata.result1);
            console.log(mydata.result1);
        }
    });
    stay.preventDefault();
});

您必须将其作为JSON返回。

Goodluck meyt

相关问题