yii与独立的post请求

一、关于返回值传递

js中的post请求

$.post(url, to_post_data, function(data){
alert(data);
if(data.msg == 'ok!') {
alert(data.msg);
}
window.location.reload();
}, 'json');



yii XXController中的actionXX返回值

function actionXX(){
//接收 请求参数
$ids = $this->request->getParam('ids');

/********** 经过一系列处理 *********/

//传回 返回值
$this->response(array('status' => 0, 'msg' => 'ok!'));
}



附1:在Controller里的request定义

public $request = null;
public function init() {
parent::init();

$this->request = Yii::app()->request;
$this->user = Yii::app()->user;

if($this->request->isAjaxRequest) {
$this->layout = false; // ajax will not render layout
}

if($this->user && $this->user->id && !$this->current_user) {
$this->current_user = User::model()->findByPk($this->user->id);
}
}

注:深刻理解this的含义。


附2:在Controller里的response方法

public function response($data, $type='application/json') {
print json_encode($data);
Yii::app()->end();
}



说明:
1,$.post要求返回json数据,所以yii返回的时候要用json_encode();
2,$.post要求返回json数据,不能掺杂任何其他数据。即不能在actionXX方法中有print_r($arr)之类的打印输出。这样才能保证是纯json格式的返回值。


二、关于post请求的参数

1,参数

var to_post_data = {};
var str="";
$("input[name='checkbox']:checkbox:checked").each(function(){
str += $(this).val()+", ";
})
to_post_data['ids'] = str.substring(0,str.length-1);


说明:
可以把看做对象,也可以看做数组,本质是包含多个名值对。
to_post_data['param1'] = param1;
to_post_data['param2'] = param2;

等同于"param1 =" + param1 + "&param2 =" + param2 + ....


2,url
var url = OMS.baseUrl + "?r=failParts/sendToManufacturer");

// var url = <?php Yii::app()->urlManager->createUrl("failParts/sendToManufacturer"); ?>
注:在js里执行该代码,暂时测试还不行。


// var _self = this;
// var url = $(_self).attr('href_url');
注:失败的原因是弄清楚this的范围。如果href_url在this范围就行。但是,大多数情况可能不行。

如果您觉得本文的内容对您的学习有所帮助,您可以微信:
[img]http://dl2.iteye.com/upload/attachment/0109/0668/fb266dfa-95ca-3d09-b41e-5f04a19ba9a1.png[/img]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值