javascript - 在 yii 中提交 ajax 表单时遇到问题

标签 javascript php jquery ajax yii

我正在创建一个在网站中使用的小部件,以在数据库中的任何字段中“查找”匹配项。我目前正在使用 jQuery“对话框”框,并希望提交表单,将表单重定向到 Controller /操作(我使用的是使用 MCV 模型的 yii),并将该函数的输出返回到当前窗口.

我目前正在使用隐藏的 div 和 jquery 加载函数。

$("#find_results").load(loadPage, function(){
}).show();

它调用一个基本上执行此操作的函数:

public function actionFind(){
    if (!empty($_POST)){
       //do really big query
       //put results into <tr> and <td> tags using a for loop
    }else{
       echo <tr><td>"no results found"</td></tr>;
    }
}

此代码返回一个输出,但仅“未找到结果”,这让我相信该表单从未真正发布。

有谁知道这里发生了什么黑魔法吗?

谢谢!

附注

该对话框是一个部分 View ,其中包含要通过操作/controller/find 提交的表单

更新:

我实现了这个:新错误是“ undefined index :findtext”,这是我的文本输入的名称。

$("#find_results").load(loadPage,{ data: $("#find_form").serialize() },function(data){
         console.log(data);
         $('#find_results').html(data);
         $(this).show();
});

最佳答案

首先,让我们看一下 signature for .load()

.load( url [, data ] [, complete ] )

url

Type: String

A string containing the URL to which the request is sent.

data

Type: PlainObject or String

A plain object or string that is sent to the server with the request.

complete

Type: Function( String responseText, String textStatus, jqXHR jqXHR )

A callback function that is executed when the request completes.

因此,如果您想将数据发送到服务器,您可以这样做:

$("#find_results").load(loadPage, {someKey: 'some value'}, function(){
          $(this).show();
});

现在,我们正在发送数据,别介意我之前所说的$_GET

来自the docs:

Request Method

The POST method is used if data is provided as an object; otherwise, GET is assumed.

此外,由于您已标记 yii,您可能需要在应用中以不同方式访问 $_POST,如下所示:

public function actionFind( ){ // pass in $request from your app
    $request = Yii::$app->request;
    if (!empty( $request->post() )){ // change this
       //do really big query
       //put results into <tr> and <td> tags using a for loop
    }else{
       echo <tr><td>"no results found"</td></tr>;
    }
}
<小时/>

参见The Definitive Guide to Yii 2.0其中说:

$request = Yii::$app->request; 
$post = $request->post();
// equivalent to: $post = $_POST;

$id = $request->post('id');
// equivalent to: $id = isset($_POST['id']) ? $_POST['id'] : null;

关于javascript - 在 yii 中提交 ajax 表单时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40042348/

相关文章:

javascript - 具有历史实现和主题标签功能的 ajax 页面加载内容

php - MySQL 和 PHP - 插入 NULL 而不是空字符串

javascript - 读取 :hover pseudo class with javascript

javascript - 模态弹出像谷歌

javascript - TEmbeddedWB.ExecScriptEx 不适用于 JavaScript

javascript - Node REPL 遵循什么 Javascript 标准?

javascript - 如何在点击时获取 css 悬停值?

php - 从客户端 DOM 序列化 SVG 的最佳方式是什么?

php - 如何在 PHP 中使用函数获取数据?

javascript - 在添加特定于过渡的 css 属性之前所做的更改会触发过渡。为什么?