GVKun编程网logo

基于js原生和ajax的get和post方法以及jsonp的原生写法实例(js原生的get和post请求)

2

以上就是给各位分享基于js原生和ajax的get和post方法以及jsonp的原生写法实例,其中也会对js原生的get和post请求进行解释,同时本文还将给你拓展Ajax中的GET和POST、ajax

以上就是给各位分享基于js原生和ajax的get和post方法以及jsonp的原生写法实例,其中也会对js原生的get和post请求进行解释,同时本文还将给你拓展Ajax 中的GET和POST、ajax中的get和post、ajax和jsonp的原生封装、AJAX的get和post等相关知识,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

基于js原生和ajax的get和post方法以及jsonp的原生写法实例(js原生的get和post请求)

基于js原生和ajax的get和post方法以及jsonp的原生写法实例(js原生的get和post请求)

<div>
<pre>
login.onclick = function(){
var xhr = new XMLHttpRequest();
xhr.open("get","http://localhost/ajax2/test2.php?username="+username.value+"&pwd="+pwd2.value,true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.status>=200 && xhr.status<300) {
alert(xhr.responseText);
};
};
}
}

Ajax 中的GET和POST

Ajax 中的GET和POST

Get和Post是两种传值方式,当我们不通过重新加载页面,用Ajax访问服务器的时候,有两个选择可以将请求信息传送到服务器上。这两个选择分别是GET和POST。Get和Post都是向服务器发送的一种请求,只是发送机制不同。

GET

GET的目的就如同其名字一样是用于获取信息的。它旨在显示出页面上你要阅读的信息。浏览器会缓冲GET请求的执行结果,如果同样的GET请求再次发出,浏览器就会显示缓冲的结果而不是重新运行整个请求。这一流程不同于浏览器的处理过程,但是它是有意设计成这样以使GET调用更有效率。GET调用会检索要显示在页面中的数据,数据不会在服务器上被更改,因此重新请求相同数据的时候会得到相同的结果。

demo示例

//获取所有商品类别 
    $.ajax({
        type: "GET",url: "/Itemmanager2/QueryItemCategory",// controller里面的方法地址
        dataType: "json",success: function (data) {
            //测试是否有数据传入
            if (data.length >= 0) {
            //alert("商品类别有数据!");
                //定义一个变量存放数据
                var data1 = [{ 'text': ' ','id': ' ' }];
                //循环,向变量里添加数据
                for (var i = 0; i < data.length; i++) {
                    data1.push({ "text": data[i].CategoryName,"id": data[i].CategoryID });   //todo:传入商品类别
                }
                //在下拉框中加载变量中的数据
                $('#cmb_itemcategory').comboBox("loadData",data1);
                $('#itemcategoryname').comboBox("loadData",data1);
            }
        },error: function (data) {
            alert("系统出错了,请联系管理员!");
        }
    })

POST

POST方法应该用于你需要更新服务器信息的地方。如某调用要更改保存在服务器上的数据,而从两个同样的POST调用返回的结果或许会完全不同,因为第二个POST调用的值与第一个的值不相同,这是由于第一个调用已经更新了其中一些值。POST调用通常会从服务器上获取响应而不是保持前一个响应的缓冲。

demo示例

function addItem() {

     if ($('#itemno').val() == '' || $('#itemname').val() == '' || $('#itembrand').val() == ''
        || $('#itemspec').val() == '' || $('#itemprice').val() == '' || $('#itemcategoryname').val() == ''
        || $('#isconsumeable').val() == '' || $('#explain').val() == '') {
        alert('请完善商品信息!');
        return;
    }
     else {
        //将页面的值传给controller
         $.ajax({
             type: "POST",url: "/Itemmanager2/additem",data: "&itemno=" + $("#itemno").val() + "&itemname=" + $("#itemname").val() + "&itembrand=" + $("#itembrand").val() + "&itemspec=" + $("#itemspec").val() + "&itemprice=" + $("#itemprice").val() + "&itemcategoryname=" + $("#itemcategoryname").val() + "&isconsumable=" + $("#isconsumable").val() + "&itemstatus=" + $("#itemstatus").val() + "&explain=" + $("#explain").val(),dataType: "json",success: function (data) {
                 alert("添加商品成功");            
             },});
    }
}

总结

如果调用是要检索服务器上的数据则使用GET。如果要检索的值会随时间和更新进程的改变而改变则要在GET调用中添加一个当前时间参数,这样后面的调用才不会使用先前的不正确的缓冲。如果调用是向服务器上发送任意数据,就可以使用POST。

ajax中的get和post

ajax中的get和post

一.谈Ajax的Get和Post的区别

Get方式:
用get方式可传送简单数据,但大小一般限制在1KB下,数据追加到url中发送(http的header传送),也就是说,浏览器将各个表单字段元素及其数据按照URL参数的格式附加在请求行中的资源路径后面。另外最重要的一点是,它会被客户端的浏览器缓存起来,那么,别人就可以从浏览器的历史记录中,读取到此客户的数据,比如帐号和密码等。因此,在某些情况下,get方法会带来严重的安全性问题。

Post方式:
当使用POST方式时,浏览器把各表单字段元素及其数据作为HTTP消息的实体内容发送给Web服务器,而不是作为URL地址的参数进行传递,使用POST方式传递的数据量要比使用GET方式传送的数据量大的多。

总之,GET方式传送数据量小,处理效率高,安全性低,会被缓存,而POST反之。

使用get方式需要注意:
1 对于get请求(或凡涉及到url传递参数的),被传递的参数都要先经encodeURIComponent方法处理.例:var url = "update.PHP?username=" +encodeURIComponent(username) + "&content=" +encodeURIComponent

(content)+"&id=1" ;


使用Post方式需注意:
1.设置header的Context-Type为application/x-www-form-urlencode确保服务器知道实体中有参数变量.通常使用XmlHttpRequest对象的SetRequestHeader("Context-Type","application/x-www-form-urlencoded;")。例:

xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
2.参数是名/值一一对应的键值对,每对值用&号隔开.如 var name=abc&sex=man&age=18,注意var name=update.PHP?

abc&sex=man&age=18以及var name=?abc&sex=man&age=18的写法都是错误的;
3.参数在Send(参数)方法中发送,例: xmlHttp.send(name); 如果是get方式,直接 xmlHttp.send(null);

4.服务器端请求参数区分Get与Post。如果是get方式则$username = $_GET["username"]; 如果是post方式,则$username = $_POST["username"];

Post和Get 方法有如下区别:
1.Post传输数据时,不需要在URL中显示出来,而Get方法要在URL中显示。
2.Post传输的数据量大,可以达到2M,而Get方法由于受到URL长度的限制,只能传递大约1024字节.
3.Post顾名思义,就是为了将数据传送到服务器段,Get就是为了从服务器段取得数据.而Get之所以也能传送数据,只是用来设计告诉服务器,你到底需要什么样的数据.Post的信息作为http请求的内容,而Get是在Http头部传输的。

get 方法用Request.QueryString["strName"]接收
post 方法用Request.Form["strName"] 接收

注意:
虽然两种提交方式可以统一用Request("strName")来获取提交数据,但是这样对程序效率有影响,不推荐使用。
一般来说,尽量避免使用Get方式提交表单,因为有可能会导致安全问题

AJAX乱码问题

产生乱码的原因:
1、xtmlhttp 返回的数据默认的字符编码是utf-8,如果客户端页面是gb2312或者其它编码数据就会产生乱码
2、post方法提交数据默认的字符编码是utf-8,如果服务器端是gb2312或其他编码数据就会产生乱码
解决办法有:
1、若客户端是gb2312编码,则在服务器指定输出流编码
2、服务器端和客户端都使用utf-8编码

gb2312:header('Content-Type:text/html;charset=GB2312');

utf8:header('Content-Type:text/html;charset=utf-8');

注意:如果你已经按上面的方法做了,还是返回乱码的话,检查你的方式是否为get,对于get请求(或凡涉及到url传递参数的),被传递的参数都要先经encodeURIComponent方法处理.如果没有用encodeURIComponent处理的话,也会产生乱码.

下边是我找到的一个例子,因为写的不错就贴在这里了,自己写的比较简单,也不是很规范还是参考人家写的好了,呵呵!

post.html:

 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
varHTTP_Request =false;functionmakePOSTRequest(url,parameters) {HTTP_Request =false;if(window.XMLHttpRequest) {// Mozilla,Safari,...HTTP_Request =newXMLHttpRequest();if(HTTP_Request.overrideMimeType) {// set type accordingly to anticipated content type//HTTP_Request.overrideMimeType('text/xml');HTTP_Request.overrideMimeType('text/html');}}elseif(window.ActiveXObject) {// IEtry{HTTP_Request =newActiveXObject("Msxml2.XMLHTTP");}catch(e) {try{HTTP_Request =newActiveXObject("Microsoft.XMLHTTP");}catch(e) {}}}if(!HTTP_Request) {alert('Cannot create XMLHTTP instance');returnfalse;}HTTP_Request.onreadystatechange = alertContents;HTTP_Request.open('POST',url,true);HTTP_Request.setRequestHeader("Content-type","application/x-www-form-urlencoded");HTTP_Request.setRequestHeader("Content-length",parameters.length);HTTP_Request.setRequestHeader("Connection","close");HTTP_Request.send(parameters);}functionalertContents() {if(HTTP_Request.readyState == 4) {if(HTTP_Request.status == 200) {//alert(HTTP_Request.responseText);result = HTTP_Request.responseText;document.getElementById('myspan').innerHTML = result;}else{alert('There was a problem with the request.');}}}functionget(obj) {varpoststr ="mytextarea1="+ encodeURI( document.getElementById("mytextarea1").value ) +"&mytextarea2="+ encodeURI( document.getElementById("mytextarea2").value );makePOSTRequest('post.PHP',poststr);}


post.PHP

<?print_r($_POST);?>
 

一个超大文本框textarea里面有大量数据,ajax通过URL请求service返回结果,URL里面包含了各种参数,当然也包含之前的超大文本框的内容。 之前开发的时候一直用Firefox在调试,4000长度的字符串在textarea里面通过URL请求都是没有问题。 提交给测试的时候问题来了,测试人员在IE下面发现问题,textarea里面字符长度超过2000(大概数据)时,会报JS错误,ajax没有返回值给前台。 看原先代码:

function getJsonData(url) { var ajax = Common.createXMLHttpRequest(); ajax.open("GET",false); ajax.send(null); try { eval("var s = "+ajax.responseText); return s; } catch(e) { return null; } } function getData(){ var url="BlacklistService.do?datas="+datasvalue; var result = getJsonData(url); }

网上google发现解决办法: 修改使用的XMLHttp的请求为POST,并且把参数和URL分离出来提交。 修改后代码如下:

function getJsonData(url,para) { var ajax = Common.createXMLHttpRequest(); ajax.open("POST",false); ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); ajax.send(para); try { eval("var s = "+ajax.responseText); return s; } catch(e) { return null; } } function getData(){ var url="BlacklistService.do"; var para="datas="+datasvalue; var result = getJsonData(url,para); }

================================

Ajax中的get和post两种请求方式的异同2008年10月04日 星期六 下午 02:37分析两种提交方式的异同

Ajax中我们经常用到get和post请求.那么什么时候用get请求,什么时候用post方式请求呢? 在做回答前我们首先要了解get和post的区别.

1、 get是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到。post是通过HTTP post机制,将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址。用户看不到这个过程。

2、 对于get方式,服务器端用Request.QueryString获取变量的值,对于post方式,服务器端用Request.Form获取提交的数据。两种方式的参数都可以用Request来获得。

3、get传送的数据量较小,不能大于2KB。post传送的数据量较大,一般被默认为不受限制。但理论上,因服务器的不同而异.

4、get安全性非常低,post安全性较高。

5、 <form method="get" action="a.asp?b=b">跟<form method="get" action="a.asp">是一样的,也就是说,method为get时action页面后边带的参数列表会被忽视;而<form method="post" action="a.asp?b=b">跟<form method="post" action="a.asp">是不一样的。

另外 Get请求有如下特性:它会将数据添加到URL中,通过这种方式传递到服务器,通常利用一个问号?代表URL地址的结尾与数据参数的开端,后面的参数每一个数据参数以“名称=值”的形式出现,参数与参数之间利用一个连接符&来区分。 Post请求有如下特性:数据是放在HTTP主体中的,其组织方式不只一种,有&连接方式,也有分割符方式,可隐藏参数,传递大批数据,比较方便。

通过以上的说明,现在我们大致了解了什么时候用get什么时候用post方式了吧,对!当我们在提交表单的时候我们通常用post方式,当我们要传送一个较大的数据文件时,需要用post。当传递的值只需用参数方式(这个值不大于2KB)的时候,用get方式即可。

现在我们再看看通过URL发送请求时,get方式和post方式的区别。用下面的例子可以很容易的看到同样的数据通过GET和POST来发送的区别,发送的数据是 username=张三 : GET 方式,浏览器键入http://localhost/?username=张三

GET /?username=%E5%BC%A0%E4%B8%89 HTTP/1.1 Accept: image/gif,image/x-xbitmap,image/jpeg,image/pjpeg,application/vnd.ms-powerpoint,application/vnd.ms-excel,application/msword,*/* Accept-Language: zh-cn Accept-Encoding: gzip,deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322) Host: localhost Connection: Keep-Alive

POST 方式:

POST / HTTP/1.1 Accept: image/gif,*/* Accept-Language: zh-cn Content-Type: application/x-www-form-urlencoded Accept-Encoding: gzip,deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322) Host: localhost Content-Length: 28 Connection: Keep-Alive

username=%E5%BC%A0%E4%B8%89

区别就是一个在 URL 请求里面附带了表单参数和值,一个是在 HTTP 请求的消息实体中。

比较一下上面的两段文字,我们会发现 GET 方式把表单内容放在前面的请求头中,而 POST 则把这些内容放在请求的主体中了,同时 POST 中把请求的 Content-Type 头设置为 application/x-www-form-urlencoded. 而发送的正文都是一样的,可以这样来构造一个表单提交正文: encodeURIComponent(arg1)=encodeURIComponent(value1)&encodeURIComponent(arg2)=encodeURIComponent(value2)&.....

注: encodeURIComponent 返回一个包含了 charstring 内容的新的 String 对象(Unicode 格式), 所有空格、标点、重音符号以及其他非 ASCII 字符都用 %xx 编码代替,其中 xx 等于表示该字符的十六进制数。 例如,空格返回的是 "%20" 。 字符的值大于 255 的用 %uxxxx 格式存储。参见 JavaScript 的 encodeURIComponent() 方法.

在了解了上面的内容后我们现在用ajax的XMLHttpRequest对象向服务器分别用GET和POST方式发送一些数据。

GET 方式 var postContent ="name=" + encodeURIComponent("xiaocheng") + "&email=" + encodeURIComponent("xiaochengf_21@yahoo.com.cn"); xmlhttp.open("GET","somepage" + "?" + postContent,true); xmlhttp.send(null);

POST 方式

var postContent ="name=" + encodeURIComponent("xiaocheng") + "&email=" + encodeURIComponent("xiaochengf_21@yahoo.com.cn"); xmlhttp.open("POST","somepage",true); xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //xmlhttp.setRequestHeader("Content-Type","text/xml"); //如果发送的是一个xml文件 xmlhttp.send(postContent);



Update from visitor "ar200r" - thank you very much

if we use "&" character it wont work...but if we use escape();var poststr = "mytextarea1=" + escape(encodeURI(document.getElementById("mytextarea1").value )) +"&mytextarea2=" +escape(encodeURI( document.getElementById("mytextarea2").value ));and next in PHP u use urldecode,it will work good.
 
转自:http://www.cnblogs.com/hateyoucode/archive/2009/12/09/1620050.html

ajax和jsonp的原生封装

ajax和jsonp的原生封装

最近在学ajax和跨域,于是就自己封装了一个,虽然有点粗糙但还是可以用的。其实jsonp的本质就是:动态创建script标签,然后通过src属性发送跨域请求,然后服务器端响应的数据格式为【函数调用(foo(实参))】,所以在发送请求之前必须先声明一个函数,并且函数的名字与参数中传递的名字要一致。这里声明的函数是由服务器响应的内容(实际就是一段js代码-函数调用)来调用。其他的就不多说了,直接上代码。

'use strict';
function ajax(obj){
var defaults = {
type:'get',
url:'#',
dataType:'text',
jsonp:'callback',
data:{},
async:true,
success:function(data){console.log(data);}
};
for(var k in obj){
defaults[k] = obj[k];
}
if(defaults.dataType == 'jsonp') {
//调用jsonp
ajaxForjsonp(defaults);
}
else {
//调用ajax json
ajaxForjson(defaults);
}
}

//json数据格式
function ajaxForjson(defaults){
//1、创建XMLHttpRequset对象
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var param = '';
for(var key in defaults.data) {
param += key + '='+ defaults.data[key] + '&';
}
if(param){
param = param.slice(0,param.length-1);
}
// 处理get请求参数并且处理中文乱码问题
if(defaults.type == 'get') {
defaults.url += '?' + encodeURI(param);
}
//2、准备发送(设置发送的参数)
xhr.open(defaults.type,defaults.url,defaults.async);
// 处理post请求参数并且设置请求头信息(必须设置)
var data = null;
if(defaults.type == 'post') {
data = param;
//设置请求头
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
}
// 3、执行发送动作
xhr.send(data);
//处理同步请求,不会调用回调函数
if(!defaults.async) {
if(defaults.dataType == 'json'){
return JSON.parse(xhr.responseText);
}
else {
return xhr.responseText;
}
}
//// 4、指定回调函数(处理服务器响应数据)
xhr.onreadystatechange = function() {
if(xhr.readyState == 4){
if(xhr.status == 200){
var data = xhr.responseText;
if(defaults.dataType == 'json'){
data = JSON.parse(data);
}
defaults.success(data);
}
}
}
}

//跨域jsonp
function ajaxForjsonp(defaults){
//cbName默认的是回调函数名称
var cbName = 'jQuery' + ('1.12.2' + Math.random()).replace(/\D/g,'') + '_' + (new Date().getTime());
if(defaults.jsonpCallback) {
cbName = defaults.jsonpCallback;
}
//这里就是回调函数,调用方式:服务器响应内容来调用
//向window对象中添加一个方法,方法名是变量cname的值
window[cbName] = function(data) {
defaults.success(data);//这里success的data是实参
}
var param = '';
for(var key in defaults.data){
param += key + '=' + defaults.data[key] + '&';
}
if(param){
param = param.slice(0,param.length-1);
param = '&' + param;
}
var script = document.createElement('script');
script.src = defaults.url + '?' + defaults.jsonp + '=' + cbName + param;
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);
}

希望能给大家带来帮助。

AJAX的get和post

AJAX的get和post

1.get

$(".shop_detail").click(function(){
    var id = $(this).attr("tag");
    $.get("/Home/Personal/downfile?id=" + id,
        function(data){
            var obj = jQuery.parseJSON(data);
            $("#product_bp_name").html(obj.bp_name);
            $("#product_bp_tel").html(obj.bp_tel);
            $("#product_bp_email").html(obj.bp_email);
            $("#product_bp_companyname").html(obj.bp_companyname);
            $("#product_bp_originator").html(obj.bp_originator);
            $("#product_bp_companyaddr").html(obj.bp_companyaddr);
            $("#product_bp_capital").html(obj.bp_capital);
            $("#product_bp_projectname").html(obj.bp_projectname);
            $("#product_bp_briefingname").html(obj.bp_briefingname);
            $("#product_bp_status").html(obj.bp_status);
            $("#product_bp_financing").html(obj.bp_financing);
            $("#product_bp_contact").html(obj.bp_contact);
            $("#product_bp_intention").html(obj.bp_intention);
        });
    $("#show_model_shop").show();
});
$(function(){
  $("#del").click(function(){
    if(confirm("确定要删除吗?")){
      var text = $("input:checkbox[name=''box'']:checked").map(function(index,elem)
      {
        return $(elem).val();    //接收显示所选复选框的内容
      }).get().join('','');
      $.get(''http://www.jjfuhuaqi.com/Admin/Newslist/delarr'',{text:text},function(msg)
      {
        if(msg==1)
        {
          $("input:checkbox[name=''box'']:checked").parent().parent().remove();
        }
        else
        {
          alert(''删除失败!'');
        }
      })
    }
  })

})

2.post

$(".shop_detail").click(function(){
    var id = $(this).attr("tag");
    $.post("/Home/Personal/bpapplys",{id:id},function(data){
            var obj = jQuery.parseJSON(data);
            $("#product_bp_name").html(obj[0].bp_name);
            $("#product_bp_tel").html(obj[0].bp_tel);
            $("#product_bp_email").html(obj[0].bp_email);
            $("#product_bp_companyname").html(obj[0].bp_companyname);
            $("#product_bp_originator").html(obj[0].bp_originator);
            $("#product_bp_companyaddr").html(obj[0].bp_companyaddr);
            $("#product_bp_capital").html(obj[0].bp_capital);
            $("#product_bp_projectname").html(obj[0].bp_projectname);
            $("#product_bp_briefingname").html(obj[0].bp_briefingname);
            $("#product_bp_status").html(obj[0].bp_status);
            $("#product_bp_financing").html(obj[0].bp_financing);
            $("#product_bp_contact").html(obj[0].bp_contact);
            $("#product_bp_intention").html(obj[0].bp_intention);
        });
    $("#show_model_shop").show();
});

注意,这里调用了A方法之后,出来的还是2维数组,需要转换成一维数组输出,要么在控制器转换,要么在视图页面转换

一:坑:

$.post("/index.php/Admin/Providerapply/providers",{id:id},

但是不能下面这样写,否则取不到数据,格式错误

$.post("/index.php/Admin/Providerapply/providers?id=" + id,

今天关于基于js原生和ajax的get和post方法以及jsonp的原生写法实例js原生的get和post请求的介绍到此结束,谢谢您的阅读,有关Ajax 中的GET和POST、ajax中的get和post、ajax和jsonp的原生封装、AJAX的get和post等更多相关知识的信息可以在本站进行查询。

本文标签: