您的位置:首页 > Web前端

JS前端知识

2016-03-15 16:55 495 查看
JSONP(JSON with Padding)是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过javascript callback的形式实现跨域访问(这仅仅是JSONP简单的实现形式)。

String callback = request.getParameter("callback");
out.print(callback+"([ { name:'John',age:'19'},{ name:'joe',age:'20'}] );");
out.print(callback);
<script type="text/javascript">
function jsonpCallback(result){
alert(result[1].name);
}
</script>
<script type="text/javascript"src="http://localhost:8080/Jsonp/jsonp.jsp?callback=jsonpCallback"></script>

<script type="text/javascript">
$.getJSON("http://localhost:8080/Jsonp/jsonp.jsp?callback=?", function(json){
alert(json[0].name);
});
</script>


$.ajax({
type : "get",
async:false,
url : "http://app.example.com/base/json.do?sid=1494&busiId=101",
dataType : "jsonp",//数据类型为jsonp
jsonp: "jsonpCallback",//服务端用于接收callback调用的function名的参数
success : function(data){
$("#showcontent").text("Result:"+data.result)
},
error:function(){
alert('fail');
}
});


 Ajax的核心是JavaScript对象XmlHttpRequest。该对象在Internet Explorer 5中首次引入,它是一种支持异步请求的技术。简而言之,XmlHttpRequest使您可以使用JavaScript向服务器提出请求并处理响应,而不阻塞用户。 
function UpladFile() {
var fileObj = document.getElementById("file").files[0]; // 获取文件对象
var FileController = "http://10.2.8.20:9797/appServlet?intertype=video";                    // 接收上传文件的后台地址
// FormData 对象
var form = new FormData();
form.append("author", "hooyes");                        // 可以增加表单数据
form.append("file", fileObj);                           // 文件对象
// XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
xhr.open("post", FileController, true);
xhr.setRequestHeader("Content-Type","application/octet-stream");
xhr.onload = function () {
alert("上传完成!");
};
xhr.send(form);
//xhr.send(fileObj);
}


json简单说就是javascript中的对象和数组,是一种轻量级的数据交换格式。

字符串转json

var obj = str.parseJSON(); //由JSON字符串转换为JSON对象

       或者

       var obj = JSON.parse(str); //由JSON字符串转换为JSON对象

eval()  会执行字符串中存在的function  安全性不高,效率不高,不建议使用

json数据增删改查(数组增删改查)

var arrayObj = new Array(); //创建一个数组
arrayObj.a="a";
arrayObj.b="b";
arrayObj.push("");
console.log(arrayObj)
delete arrayObj[0];//置空 不完全删除 数组length不变( 通过下标操作数组)
console.log(arrayObj)
arrayObj.push("");
console.log(arrayObj.length)
arrayObj.splice(0,1);//开始位置,删除个数 完全移除
console.log(arrayObj.length)
delete  arrayObj.a;//删除json对象 (通过.属性名操作json)
console.log(arrayObj)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js ajax json