开发者

Can a Jquery Ajax Call Accept an Object on Succes from PHP?

I'm writing a simple ajax function and looking to populate two text input fields with the 'success' results. I'm wondering what my php syntax has to be to return an object.

Here is my Javascript function

function editModule(a){
    data = {moduleNum:a}
    $.ajax({
        t开发者_开发技巧ype: 'POST',
        data: data,
        url: 'includes/ajaxCalls.php',
        success: function(data) {
            alert(data['title']); // <-- This is where I'm not sure what to return from php
        }
    });
}

Here is my php doc (so far, this is where I need to know how to return an object)...

<?php
$data =  array('title'=>'this');
echo json_encode($data);

When I run the function I just get the alert "undefined".

Suggestions?

Thanks, -J


Try this. You can specify that you're expecting a JSON object and then you can interpret data accordingly.

function editModule(a){
    data = {moduleNum:a}
    $.ajax({
        type: 'POST',
        data: data,
        dataType: 'json',
        url: 'includes/ajaxCalls.php',
        success: function(data) {
            alert(data.title);
        }
    });
}


I have returned JSON data from the server via a jQuery Ajax call, not in PHP but it should be the same. As long as you set the content-type of your response to application/json jQuery should consider the responseText as a JSON string. Alternatively you can also set dataType: "JSON" in your Ajax call which tells jQuery that you expect JSON.


Your php page returns: {"title":"this"} in this case. So you can reference the result with:

alert(data.title);


You may need to specify the data type:

function editModule(a){
    data = {moduleNum:a}
    $.ajax({
        type: 'POST',
        data: data,
        url: 'includes/ajaxCalls.php',
        dataType: 'json',
        success: function(data) {
            alert(data['title']); // <-- This is where I'm not sure what to return from php
        }
    });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜