我正在使用 Yii 框架,我想通过将一些数据从 js 发送到 php 函数而不离开表单页面来提交表单,我怎样才能简单地做到这一点?
最佳答案
如果你想知道 Yii 生成 ajax 请求的方式,例子如下,
在发送ajax请求的页面中您的 View
Yii::app()->clientScript()->registerScript("someid",
CHtml::ajax(array(
'url'=>array('controller/action'),
'type'=>'POST', //
'dataType'=>'json',// or html
'data'=>array(
'js_id'=>'js:id', // you can bind js vars using js: prepend like this
'php_id'=>$id, // or if the values are known at pageload you can use php vars like this
),
'success'=>'js:function(json){
//Do some thing here
}'
// Any other option supported by Ajax
)
)
,CClientScript::POS_END);
// POS_READY, POS_LOAD, POS_HEAD etc available depending on where and how you want load the script
注意这不是在页面中使用 ajax 的简单或容易的方法,但它与 Yii 集成,因此它很有用,例如,如果您更改应用程序的路由逻辑,您的所有ajax 中的路由已经处理完毕,使用此方法也可以轻松将 CSRF token 添加到 POST 请求等
关于javascript - 如何从js发送数据而不保留当前url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24343520/