将ajax变量Jquery到php中

Jquery ajax variables into php

本文关键字:php Jquery ajax 变量      更新时间:2023-09-26

嗨,在使用jquery ajax函数将一些变量从javascript传递到php之后,我正在尝试检索响应。

这是jquery ajax代码:

$(document).ready(function() {
    $("#invoice_submit_button").click(function() {
        var action = $("invoice_form").attr('action');
        $.ajax({
            type: "POST",
            url: action,
            data: $('form#invoice_form').serialize(),
            dataType: "json",
            success: function(response) {
                if (response.error == 'none') {
                    $("#ajax_response").html("<p>" + response.msg + "</p>");
                }
                else {
                    $("#ajax_response").html("<p>" + response.msg + "</p>");
                }
            }
        });
        return false;
    });
});

(ofc根据响应会有不同的输出。当它工作时出错,这只是一个例子)

这是php代码:

$msg="Bla bla";
$error="form_err";
$result = array('msg' => $msg, 'error' => $error);
$result_json = json_encode($result);
echo $result_json;

使用firebug进行调试表明,发布部分没有问题,但看起来脚本无法从php获得响应(并将其打印到目标div中)。我遗漏了一些东西,我对其他脚本使用了相同的方法,而且一直有效。感谢

您是否尝试在PHP脚本中将内容类型设置为application/json?

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

action为空,因为jQuery找不到元素invoice_form

$("invoice_form").attr('action');应该是$("#invoice_form").attr('action');

您确定请求发送到了正确的URL吗?