Vue+Axios+transformToJson

版权声明:转载原创文章请以超链接形式请注明原文章出处,尊重作者,尊重原创!


恰饭广告




<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf8" />

<head></head>

<body>
<div id="app"></div>
	<form id="register">
		<input type="text" name="user" value="hpc"><br> <input
			type="text" name="pwd" value="123"><br> <input
			type="text" name="sex" value="M"><br> <input type="text"
			name="age" value="100"><br> <input type="text"
			name="phone" value="13011112222"><br> <input type="text"
			name="email" value="xxx@xxx.com"><br>
	</form>
	<input id="switch" type="button" value="switch">
</body>
<script type="text/javascript"
	src="https://www.idaobin.com/js/jquery-3.2.1.js"></script>
<script src="https://www.idaobin.com/js/axios-0.19.js"></script>
<script src="https://www.idaobin.com/js/vue-2.6.10.js"></script>
<script type="text/javascript">
	// 转为json数据格式 传入表单id
	function transformToJson(register){
		var register = $("#"+register);
		//返回字符串xxx=xxx&yyy=yyy;
		var formData = register.serialize();
		// 返回的是json数组[{xxx:xxx},{yyy:yyy}]
		formData = register.serializeArray();
		var obj = {}
		for (var i in formData) {
			/*[{"name":"user","value":"hpc"},{"name":"pwd","value":"123"},{"name":"sex","value":"M"},{"name":"age","value":"100"},{"name":"phone","value":"13011112222"},{"name":"email","value":"xxx@xxx.com"}]
			*/
			//下标为的i的name做为json对象的key,下标为的i的value做为json对象的value
			obj[formData[i].name] = formData[i]['value'];
		}
		return JSON.stringify(obj);
	}


	var vue = new Vue({
			el : "#app",
			data : {
				//传入参数
				send : {
					param : "",
					op : ""
				}
			},
			// created: function () {
			// 	this.loadData(); //页面加载
			// },
			methods : {
				loadData : function() {
					this.send.param=transformToJson("register");
					this.send.op="update";
					axios.post('SwitchJson', this.send, { //请求地址
						transformRequest : [
							function(data) {
								let params = '';
								for (let index in data) {
									params += index + '=' + data[index] + '&';
								}
								return params.substring(0, params.length - 1);
							}
						]
					}).then(resp => {
						//获取返回的json
						console.log(resp.data);
					}).catch(error => {
						console.log('请求失败:' + error.message);
					});
				}
			},
		});
		

	$("#switch").click(function() {
		vue.loadData();
	});

	
</script>

原文链接:https://www.idaobin.com/archives/2134.html

让我恰个饭吧.ヘ( ̄ω ̄ヘ)

支付宝 ——————- 微信
图片加载中图片加载中



恰饭广告

发表评论

电子邮件地址不会被公开。 必填项已用*标注

16 ÷ 8 =