-1

将 jquery 与 php 一起使用时,是否可以将数据以 HTML 格式发送但以 json 格式接收数据?在我的情况下,我将表单数据作为 HTML 发送,因为 json 只能处理字母数字数据。如果表单包含错误,则返回一个错误消息数组,我会将其附加到错误消息 div 中,如果没有,则重定向用户。是否有可能做到这一点?我应该指定什么数据类型,我应该使用 json_encode 返回数组

$("#sform").submit(function() {
    $.ajax({
        type: "POST",
        data: $(#sform).serialize(),
        cache: false,
        //What data type to sepcify here? Data goes as HTML but returns as json
        url: "user_verify.php",
        success: function(data) {
            //Print the php arrays data here to errormessage divs
        }
    });
    return false;
});
4

2 回答 2

0

使用dataType : 'json'如果您jsonphp

$("#sform").submit(function() {
    $.ajax({
        type: "POST",
        data: $(this).serialize(),
        cache: false,
        //What data type to sepcify here? Data goes as HTML but returns as json
        url: "user_verify.php",
        success: function(data) {
            //Print the php arrays data here to errormessage divs
        },
        dataType:'json'
    });
    return false;
});

PS:在您的问题i'm sending form data as HTML中,但您使用的是.serialize()API,这意味着您正在以字符串形式发送数据编码。所以你没有发送任何 HTML

于 2012-08-19T06:05:53.093 回答
0

要告诉服务器您期望返回的数据类型,请使用以下dataType参数:

$("#sform").submit(function() {
    $.ajax({
        type: "POST",
        data: $(#sform).serialize(),
        cache: false,
        dataType: 'json',
        url: "user_verify.php",
        success: function(data) {
            //Print the php arrays data here to errormessage divs
        }
    });
    return false;
});

If you don't specify dataType then $.ajax will try to guess the type based on the header sent back from the server.

In your case, you can also add this to your php page:

header('Content-type: application/json');

and as you stated, return your data with json_encode().

If you don't to POST data, you can also check out the getJSON() method: http://api.jquery.com/jQuery.getJSON/

note: using dataType AND setting the content-type to application/json may be redundant, but it can add clarity.

于 2012-08-19T06:09:21.433 回答