【问题标题】:AJAX call to PHP receives the "previous" posted data对 PHP 的 AJAX 调用接收“以前”发布的数据
【发布时间】:2014-08-31 03:23:03
【问题描述】:

所以我使用 jQuery 表单扩展从表单发布数据。当用户在 HTML 页面上按下["Save"] 时,会执行此代码。

$('#myform').ajaxForm({
    async: false,
    cache: false,
    target: $(this).find('.save-response'),
    beforeSubmit: function(arr,$form){
        json_ = JSON.stringify (vars.table_settings[aux.getTableId()].by_ix); //, null, 4);
        $form.find('.user-settings').val(json_);
        $form.find('.save-response').stop(true,true).hide().show();
        alert (json_);
    },
    success: function(){
        $(this).fadeOut(15000);
    },

如您所见,我使用 alert() 函数来检查 AJAX 调用中实际传递到目标 PHP 文件的内容。我看到的是以下内容:

[
...
{"id":"colpartdesc","vis":"vis","width":500,"ix":3,"desc":"Part Desc."},
...
]

在 PHP 文件中,我读取了 $_POST 值,并将其反馈给调用页面(在本例中为 .save-response 元素)作为响应。我得到的答复是这样的:

[
...
{"id":"colpartdesc","vis":"vis","width":270,"ix":3,"desc":"Part Desc."},
...
]

如您所见,"width" 值不同。事实上,270 的值是我上次按下["Save"] 按钮时发送的值。如果我再次按下["Save"],服务器将收到此调用中发送的500 值。但可能到时候500的值是错误的。

如果我在更改输入之前每次按两次["Save"] 按钮,则该功能按预期工作。

如您所见,我在 Ajax 调用中禁用了 cache,所以我认为这不是问题。

有人知道我为什么会遇到这种行为吗?

除此之外:原始 HTML 页面是使用 Smarty 模板引擎生成的。但是,我也关闭了 Smarty 引擎中的缓存,所以我再次认为这并不重要。此外,处理 Ajax 调用的 PHP 文件不使用 Smarty 模板。

【问题讨论】:

    标签: php jquery ajax forms


    【解决方案1】:

    问题的答案是我不知道jQuery Form插件是如何工作的。

    jQuery Form 提交的不是表单字段中的值,而是数组中的值。因此,使用beforeSubmit 函数更新表单本身的值(如下行所示)是不正确的:

    $form.find('.user-settings').val(json_);
    

    我应该做的是更新表单数据数组,如下所示:

    $('#myform').ajaxForm({
        $(this).ajaxForm({
            target: $(this).find('.save-response'),
            beforeSubmit: function(formData,$form){
                json_ = JSON.stringify (vars.table_settings[aux.getTableId()].by_ix); //, null, 4);
                formData[1].value = json_;
                $form.find('.save-response').stop(true,true).hide().show();
            },
            success: function(){
                $(this).fadeOut(15000);
            },
        });
    

    >>this<< 帖子的答案让我走上了正轨。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-06
      • 2013-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-21
      • 1970-01-01
      相关资源
      最近更新 更多