0

我正在使用 jQuery,控制台返回我:

Data Loaded: [object Object]

jQuery:_

$(document).ready(function(){
    //Button click event

    $("#ajaxForm").submit(function(e){
        // disable the form submit
        e.preventDefault();
    });
    /* get some values from elements on the page: */
    var $form = $( this ),
    term = $form.find( 'input[name="id"]' ).val(),
    url = $form.attr( 'update' );


    /* Send the data using ajax */
    var posting =
        $.ajax({
            url: url
        });

    $.post(url, { id: term } ).done(function(data) {
        console.log("Data Loaded: " + data);
        $("#result").empty().append(data);      
    });
});

我如何将“json”的结果转换为“字符串”。谢谢。

4

4 回答 4

2

试试这个

JSON.stringify(data);
于 2013-02-26T10:36:43.847 回答
1

要将 JSON 对象转换为字符串,请使用以下代码。

JSON.stringify(data);

“数据”是您的 JSON 对象。

要将字符串转换回 JSON 对象,请使用以下代码。

JSON.parse(String);
于 2013-02-26T10:49:06.730 回答
0
$.post(url, returnFunction(data){...}, 'text'); 

将确保它data是文本格式,但如果您改为执行以下操作:

$.post(url, returnFunction(data){...}, 'json');

然后 jQuery 会自动确保data是一个 JSON 对象。

请注意,jQuery 将尝试智能地猜测数据是什么并传回正确的对象,放置“text”或“json”只是为了明确这一点。

于 2013-02-26T10:44:46.693 回答
0

返回 json 不正确。通过单击“提交”表单并希望返回一个 JSON。表格被退回。

脚本正确吗?

$("#ajaxForm").submit(function(e){
    // disable the form submit
    e.preventDefault();
});

在这种情况下,事件不起作用,但提交按钮不起作用。

form.html。_

< form action = "update" method = "post" id = "ajaxForm" >
        < fieldset class = "success" >
        < legend > The fields marked with * . < /legend>
        < div >
        < label for = "destination" class = "block" >
        host:
        < span class = "mandatory_asterisk" > * < /span>
        < /label>
        < select id = "destination" class = "select" name = "destination" >
        < option value = "element1" > element1 < /option>
        < option value = "element2" > element2 < /option>
        < /select>
        < /div>
        < div >
        < span class = "infoTrigger" > Update a page of the search < /span>
        < label for = "id" class = "block" >
        page
you want to index:
        < /label>
        < input type = "text" class = "text" id = "page" name = "page"
        value = "" / >
        < /div>
        < div >
        < span class = "infoTrigger" > Update a certain id of the host < /span>
        < label for = "id" class = "block" >
        id
on the host (e.g. element1 - id - post - json):
        < /label>
        < input type = "text" class = "text" id = "id" name = "id"
        value = "" / >
        < /div>
        < !-- < input id = "operation" type = "submit" / > -- >
        < input type = "submit" value = "update" name = "update" id = "operation" / >
        < /fieldset>
        < div id = "anotherSection" >
        < fieldset >
        < legend > Response from jQuery Ajax Request < /legend>
        < div id = "result" > < /div>
        < /fieldset>
        < /div>
        < /form>
于 2013-02-26T11:26:51.200 回答