(编辑:jimmy 日期: 2024/11/18 浏览:2)
以下代码如果需要在你本地跑起来:
Ⅰ.需要apache服务,并把php代码丢进去指定位置
Ⅱ.将下面http://www.test.com/day05/jiekou.php地址,改成自己指定位置的域名或ip
1.从一段简易代码说起
前端代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <!-- 导入axios --> <script src="/UploadFiles/2021-04-02/axios.min.js">php接口代码
<"Access-Control-Allow-Origin:*"); // 允许的响应类型 header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH'); // 响应头设置 header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization"); // 获取form表单值 $username = $_POST['username']; $password = $_POST['password']; // 判断form表单中key if(isset($_POST['username']) && isset($_POST['password'])){ // 判断username和password if($username == "admin" && $password == "123456"){ $result = array("success" => 1, "code" => 101, "data" => array("username" => $username, "password" => $password)); }else{ $result = array("success" => 0, "code" => 103, "data" => null); } }else{ $result = array("success" => 0, "code" => 100, "data" => null); } // 将错误信息(数组)转换成json类型,返回前端 echo(json_encode($result)); "text-align: center">2.解决:
方法Ⅰ.引入qs模块处理数据:修改上面的html代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <!-- 导入axios --> <script src="/UploadFiles/2021-04-02/axios.min.js">方法Ⅱ.后端开放options请求跨域,并用对应的方法获取options提交的复杂数据
<"Access-Control-Allow-Origin:*"); // 响应类型 header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH'); // 响应头设置 header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization"); //如果是options请求,就结束执行下面语句 if($_SERVER['REQUEST_METHOD']=='OPTIONS'){ //exit是用来结束程序执行的,如果参数是字符串,PHP将会直接把字符串输出, //如果参数是整型(范围是0-254),那个参数将会被作为结束状态使用。 exit('options类型的请求,结束'); } //option请求无法用常规方法($_GET, $_POST, $_REQUEST)获取请求参数 $option_data_str = file_get_contents("php://input"); $option_data = json_decode($option_data_str,true); $username = isset($option_data['username'])""; $password = isset($option_data['password'])""; // 判断form表单中key if(isset($username) && isset($password)){ // 判断username和password if($username == "admin" && $password == "123456"){ $result = array("success" => 1, "code" => 101, "data" => array("username" => $username, "password" => $password)); }else{ $result = array("success" => 0, "code" => 103, "data" => null); } }else{ $result = array("success" => 0, "code" => 100, "data" => null); } // 将错误信息(数组)转换成json类型,返回前端 echo(json_encode($result)); "_blank" href="https://www.npmjs.com/package/qs">https://www.npmjs.com/package/qs)
qs.parse()将URL解析成对象的形式
qs.stringify()将对象 序列化成URL的形式,以&进行拼接(我们大都用到这个)
"htmlcode">
import qs from 'qs'; Vue.prototype.$qs = qs;在所有的vue实例组件里都可以直接用this.$qs.stringify(要处理的数据),进行数据转换
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。