使用http.post()发送数据到php作为服务器端
我想在Angular2中使用http.post()发送一个对象到后端,并且我已经使用了以下代码。我无法将数据发送到后端。对于使用codeigniter框架的服务器端编程。我不知道代码有什么问题。我应该对m个component.ts做些什么改变?使用http.post()发送数据到php作为服务器端
component.ts
let headers = new Headers();
headers.append('Content-Type', 'application/json; charset=UTF-8');
let addcategory_body={
'name':this.add_ser_name,
'description':this.add_ser_name,
'icon':'asfsdfdf.png'
}
this.http.post('http://www.viarchtechnologies.com/projects/coolmanz/index.php/ws/service', addcategory_body, {
headers: headers
}).subscribe(res => {
console.log('post result %o', res);
});
编辑
ws.php
public function service() {
$this->load->model('Coolmodel','m',true);
$retval = array();
$icon = '';
if($_POST) {
$id = $this->input->post('id');
$name = $this->input->post('name');
$description = $this->input->post('description');
$active = $this->input->post('active');
$deleted = $this->input->post('deleted');
$display_order = $this->input->post('display_order');
$icon = $this->input->post('icon');
if($name == '') {
$retval['status'] = '0';
$retval['error'] = 'name missing';
} else if($description == '') {
$retval['status'] = '0';
$retval['error'] = 'description missing';
} else {
if($active == '') {
$active = 1;
}
if($deleted == '') {
$deleted = 0;
}
if($display_order == '') {
$display_order = $this->m->get_nextOrder_Service();
}
$data = array(
'name' => $name,
'active' => $active,
'icon' => $icon,
'description' => $description,
'deleted' => $deleted,
'display_order' => $display_order
);
$retval['status'] = '1';
if($id == '') {
$this->m->saveToDB('services', $data);
} else {
$data['modified'] = date('Y-m-d H:i:s');
$this->m->updateDB('services', $data, 'id', $id);
}
//$user=$this->m->login($userlogin, md5($password));
}
} else {
$services = $this->m->get_services();
$retServices = array();
$i = 0;
foreach($services as $service) {
if($service['icon'] != '') {
$service['icon'] = base_url().'images/'.$service['icon'];
}
$retServices[$i++] = $service;
}
$retval['status'] = '1';
$retval['services'] = $retServices;
}
header('Content-Type: application/json');
echo json_encode($retval, JSON_UNESCAPED_UNICODE);
}
[![Respose][1]][1]
是您从$_POST
变量,而您发送期待值的问题10身体是一个json
对象。你的功能服务现在不会。
尝试这个办法:更换你的if
声明,你检查POST
数据:
if($this->input->method() === 'post') {
$obj = json_decode($this->input->raw_input_stream);
$id = $obj->id;
$name = $obj->name;
$description = $obj->description;
$active = $obj->active;
$deleted = $obj->deleted;
$display_order = $obj->display_order;
$icon = $obj->icon;
}
试试吧,让我们知道您的结果请: - | +1 –
对你有帮助吗? ) –
是的,它解决了我的问题,运作良好 –
有什么错误? http请求是否被触发?我们需要更多信息来排除故障 – LLai
您是否会遇到'cors'错误?如果是的话,你必须在服务器端配置'cors'。否则需要更多关于确切错误的细节。 – Kuncevic
请提供你有什么错误。此外你的网址有2个空的空间,可能会导致问题.../coolmanz /index.php – Mehdi