原生JS实现向后端提交Post请求

页面跳转的方式实现提交请求,使用<script>location.href='www.yixzm.cn'</script> 即可,不用详述。

不使用页面跳转的方式实现页面刷新后端数据,需要使用发送Post请求的方式。

HTML只有一个 <textarea>

<textarea id='writeFictionArea'>info->txt</textarea>

JS实现获取<textarea> 的内容,并提交给Server。本文使用虚拟表单的方法实现,具体使用了三个功能,分别是POST提交方法,调用方法,及后台输出。

实现POST请求提交

function post(URL, PARAMS) {
    window.alert('xxx');
    var temp = document.createElement('form');
    temp.action = URL;
    temp.method = 'post';
    temp.style.display = 'none';
    for (var x in PARAMS) {
        var opt = document.createElement('textarea');
        opt.name = x;
        opt.value = PARAMS[x];
        //alert(opt.value);
        //alert(opt.name);
        temp.appendChild(opt);
    }
    document.body.appendChild(temp);
    temp.submit();
    return temp;
}       

调用者只需要传入参数即可。本文传的内容是标签<textarea>中的文本数据。当按键为Ctrl+S(Mac本输入Mate+S) 时提交。

window.addEventListener('keydown', function(e){
    var title = document.getElementById('writeFictionArea').value;
    var content = document.getElementById('writeFictionArea').value;
    if (e.keyCode == 83 && (navigator.platform.match('Mac') ? e.metaKey : e.ctrlKey)) {
        e.preventDefault();
        //window.alert('保存成功');
        //window.alert(content);
        post('http://localhost/writefiction',{title:'prnhtml', content:content});
    }
}, false);

后端输出接收到的POST请求,本文以PHP的方法实现,其它场景可类比。

if (isset($_POST['content'])) {
    echo $_POST['content'];
}

效果图示如下:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/dreamstone_xiaoqw/article/details/80000909
今日推荐