$post(url,{}).done.function(data){}中data出现undefined

$post(url,{}).done.function(data){}中data出现undefined,前端debugger,在network中有403错误,代码是要判断浏览器的,function方法体里的代码不执行,是什么问题啊,求大神解答,参数一个为字符串,一个是数字,var定义,后台控制器好像也没进去,但url地址是对的

1个回答

如果 URL 请求返回是 403 ,说明该请求被服务器端拒绝处理了,可能是权限问题导致的。
需要看看这个 URL 请求具体是干什么的,路径是否正确,后台有什么访问控制策略等。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
关于IE跨域利用JQuery的XDomainRequest插件的使用方法
代码如下,我用了两个JQuery版本,一个是1.5.1一个是1.11.0,在浏览器都报了一样的错误:JQuery未定义。服务器端也是按照网上的写法写的 $.ajax({ url: URL + "/www/doLogin.dc", data: { mobile: mobile.val(), password: password.val() }, contentType: 'text/plain', type: 'POST', dataType: 'html' }).done(function(data) { if(data.result == "1") { //输入正确 console.log("请求返回成功信息"); } else { //输入错误 $("#err").attr("style", "display:block"); $("#err").html(data.message); return false; } });
为什么我的 JavaScript 代码在所请求的资源上没有出现“Access-Control-Allow-Origin'header”错误
而Postman就没问题? 我正在尝试通过连接到内置在 Flask 中的 RESTful API 来使用 JavaScript 进行授权。 但是,当我提出请求时,我会得到以下错误: 无法加载 http://myapiurl/login。 请求的资源上没有“访问控制允许原点”头。 因此,“ null”是不允许访问的。 我知道 API 或远程资源必须设置表头,但为什么当我通过 Chrome 扩展Postman发出请求时,它还能工作呢? 请求代码如下: ``` $.ajax({ type: "POST", dataType: 'text', url: api, username: 'user', password: 'pass', crossDomain : true, xhrFields: { withCredentials: true }}) .done(function( data ) { console.log("done"); }) .fail( function(xhr, textStatus, errorThrown) { alert(xhr.responseText); alert(textStatus); }); ```
ajax无法发送请求,后台也未接收到请求
试了很多次,表单提交后,到alert(data)一句(包括这一句)都执行正常,但之后的ajax语句就无法发送请求,ajax语句里面的几个alert也没有运行,最后的alert('1')也没有运行(异步请求正常运行的话应该是会执行的吧) 以下是前端代码,本来代码是要复杂些的,但我调试的时候把代码简化了,基本确定是ajax语句的问题了。 ``` $(function () { 'use strict'; $('#login_form').submit(function (event) { event.stopPropagation(); event.preventDefault(); var nickname = $('#login_form').find('#login_nickname').val(); var pwd = $('#login_form').find('#login_password').val(); if (!nickname || !pwd) { $('#login_text').show(); } var raw_data = { title: 'login', nickname: nickname, password: pwd } var data = JSON.stringify(raw_data); alert(data); $.ajax('/login', { dataType: 'json' }).done(function (data) { alert('成功'); }).fail(function (xhr, status) { alert('失败'); }).always(function () { alert('请求完成: 无论成功或失败都会调用'); }); alert('1'); }); }); ``` 后端代码如下,用的是flask。按理来说即便url不对,后台也应该有请求记录的,然而后台并没有显示该记录 ``` @app.route('/login',methods=['POST',]) def login(): if g.user is not None and g.user.is_authenticated: flash('You have already logged in!') return redirect(url_for('home')) raw_data=request.get_data() print(raw_data) data=json.loads(raw_data) print(data[pwd],data[nickname]) resp=dict(success = True,text ='limbohotmore!') return json.dumps(resp) ``` 后台记录如下,无论提交几次表单,都只有第一次获取主页面的请求记录 ``` * Restarting with stat * Debugger is active! * Debugger PIN: 289-281-425 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) 127.0.0.1 - - [26/Jul/2019 12:52:27] "GET / HTTP/1.1" 200 - ```
vue的vuescroll插件苹果手机滑动不了,安卓手机没有问题
大佬们救助啊!!! ```<template> <div style="margin-top:-80px;"> <div class="page__hd"> <div class="weui-form-preview__ft"> <label class="weui-form-preview__btn weui-form-preview__btn_default"> <span @click="toIndex" style="color:rgb(0, 0, 0);">&lt;返回</span> </label> <label type="submit" class="weui-form-preview__btn weui-form-preview__btn_primary" href="javascript:" style="color:rgb(0, 0, 0);" >{{this.zqName}}合同</label> <label type="submit" class="weui-form-preview__btn weui-form-preview__btn_primary" style="color:rgb(0, 0, 0);" @click="select" > 筛选 <img src="../assets/000.png" height="20px" width="20px" /> </label> </div> </div> <div class="pr-wrap_tra" style=" overflow-y: scroll;touch-action: pan-y;-webkit-overflow-scrolling: touch;"> <div class="wrap-part_tra first_tra" > <vuescroll ref="vs" :ops="ops" @refresh-start="handleRS" @load-before-deactivate="handleLBD" @refresh-before-deactivate="handleRBD" @load-start="handleLoadStart" > <div v-for="item in ContractList" :key="item.dictid"> <div class="contractList_css_tra"> <div class="list_css_tra" @click="jumppage(item.dictid)"> <span style="float:left;">{{item.farmername}}</span> <span style="float:right;" v-if=" item.isrecord=== 0">糖厂未上报</span> <span style="float:right;" v-if=" item.isrecord=== 1">乡政府退回</span> <span style="float:right;" v-if=" item.isrecord=== 2">县政府退回</span> <span style="float:right;" v-if=" item.isrecord=== 5">糖厂已上报</span> <span style="float:right;" v-if=" item.isrecord=== 6">乡政府已上报</span> <span style="float:right" v-if=" item.isrecord=== 7">县政府已备案</span> <br /> <span style="color:#4169E1;float:left;margin-top: -5px;">({{item.ocnum}})</span> <!-- <p style="float:left; font-size:15px; color:#C0C0C0; margin-top: 5px" >&nbsp;&nbsp;{{item.signdate}}</p> --> <br /> <hr style="width: 100%;" /> <div class="tr_css_tra"> <table class="table_css_tra"> <tr class="title_tra"> <td>种植面积</td> <td>种植产量</td> <td>风险值</td> </tr> <tr class="content_tra"> <td>{{item.area?item.area.toFixed(2):0}} <span style="font-weight:bold;font-size: 13px;">亩</span> </td> <td>{{item.yeild?item.yeild.toFixed(2):0}} <span style="font-weight:bold;font-size: 13px;">吨</span></td> <td v-if=" item.isrecord == 0"> <span style="font-weight:bold;font-size: 13px;">-</span></td> <td v-if=" item.isrecord > 0 && item.matchstate ==0"> <span style="font-weight:bold;font-size: 13px;">计算中</span></td> <td v-if=" item.isrecord > 0 && item.matchstate ==1"> {{item.riskevaluation}} <span style="font-weight:bold;font-size: 13px;">%</span></td> </tr> </table> </div> <hr style="width: 100%;" /> <span style="float:left; margin-top: 10px; ">{{item.departname?item.departname:''}}</span> <span style="float:right; margin-top: 10px;">详情></span> </div> </div> </div> <div id="nodata" style="display:none">{{this.context}}</div> </vuescroll> </div> </div> </div> </template> <script> import vuescroll from "vuescroll"; import farmers from "@/api/farmers"; import indexApi from "@/api/index"; import Vue from "vue"; import axios from "axios"; export default { name: "myvuescroll", props: { // 语言 lang: { default: "zh" // en }, // 距离底部触发自动加载的距离 autoLoadDistance: { default: 10 }, // 是否开启下拉刷新 isRefresh: { default: true }, // 是否开启上拉加载 isPushLoad: { default: true }, // 数据是否全部加载完成 true为全部加载完成 noData: { default: false }, // 下拉刷新开始 refreshStart: { default: () => {} }, // 下拉刷新完成之后 refreshDeactivate: { default: () => {} }, // 上拉开始 loadStart: { default: () => {} }, // 上拉完成之后 loadDeactivate: { default: () => {} } }, components: { vuescroll }, data() { const config = {}; const ops = { vuescroll: { mode: "slide", pullRefresh: { enable: this.isRefresh }, pushLoad: { enable: this.isPushLoad, auto: true, //是否自动触发加载 autoLoadDistance: this.autoLoadDistance } } }; if (this.lang == "zh") { ops.vuescroll.pullRefresh.tips = { deactive: "下拉刷新", active: "释放刷新", start: "刷新中...", beforeDeactive: "刷新成功!" }; ops.vuescroll.pushLoad.tips = { deactive: "上拉加载", active: "释放加载", start: "加载中...", beforeDeactive: "加载成功!" }; } return { ops, config, pageNo: 1, isfirstload: false, end: 0, is: true, ContractList: [], zqName: "", minrisk: 0, maxrisk: 0, farmersName: "", contractCode: "", record: "", data: {}, zqCode: "", departCode: "", xzCode:"", user:{}, sx:true, xl:true, presser:'', context:'', //, maxarea:0, // minarea:0, // isrecord:0, // ocnum:0, // farmername:'' }; }, // created: function() { // this.myInstalHomeFun(); // }, created:function(){ this.user = this.$route.params.user; this.zqCode = this.$route.params.zqCode; this.departCode = this.$route.params.departCode; this.xzCode=this.$route.params.xzCode; this.zqName = this.$route.params.zqName; this.presser = this.$route.params.presser; }, mounted: function() { this.minrisk = this.$route.params.minrisk; this.maxrisk = this.$route.params.maxrisk; this.farmersName = this.$route.params.farmersName; this.contractCode = this.$route.params.contractCode; this.record = this.$route.params.record; this.FarmersContractList(); //需要触发的函数 // alert(this.minrisk) // alert(this.maxrisk) // alert(this.farmersName) // alert(this.contractCode) // alert(this.record) }, methods: { // FarmersContractList() { // let _this = this; // axios({ // url: // "/api/cloudec/fo/order/OrderContractController/GetOrderContractPage", // method: "post", // data: { // pageNo: 1, // pageSize: 10 // this.data=this.$route.query; // // this.maxarea=this.$route.query.maxarea; // // this.minarea=this.$route.query.minarea; // // this.isrecord=this.$route.query.isrecord; // // this.ocnum=this.$route.query.ocnum; // // this.farmername=this.$route.query.farmername; // }, // 刷新开始 // vsInstance vm===this // refreshDom === 刷新dom handleRS(vsInstance, refreshDom, done) { if (this.refreshStart) { this.refreshStart(done); } else { //this.setDone1(done); done(); } }, // 刷新完之后 handleRBD(vm, loadDom, done) { if (this.refreshDeactivate) { this.refreshDeactivate(done); } else { setTimeout(() => { this.setDone1(done); }, 600); } }, // 上拉开始 handleLoadStart(vm, dom, done) { if (this.loadStart) { this.loadStart(done); } else { if (this.isfirstload) { //this.setDone(done); done(); } else { done(); this.isfirstload = true; } } }, // 上拉完成后 handleLBD(vm, loadDom, done) { if (!this.$parent.noData) { if (this.loadDeactivate) { this.loadDeactivate(done); } else { setTimeout(() => { this.setDone(done); //done(); }, 600); } } else { setTimeout(() => { this.setDone(done); //done(); }, 600); } }, // 手动触发 外部通过ref触发 // type load 为加载 refresh 为刷新 trigger(type = "load") { this.$refs["vs"].triggerRefreshOrLoad(type); }, setDone(done) { if(this.sx){ this.pageNo++; this.FarmersContractList(); } done(); }, setDone1(done) { if(this.xl){ this.xl=false; this.ContractList = []; this.is=true; this.pageNo = 1; this.FarmersContractList(); } done(); }, FarmersContractList(done) { let _this = this; if (_this.is) { indexApi.FarmersContractList(this.pageNo,this.maxrisk,this.minrisk,this.record,this.contractCode,this.farmersName,this.departCode, this.zqCode,this.presser,this.xzCode,this.zj) .then(function(response) { // response.data中获取ResponseData实体 // alert(response); if(response.data.pageSize==0){ _this.context="暂无数据"; } for (var i = 0; i < response.data.page.dataList.length; i++) { _this.sx=false; _this.xl=false; _this.ContractList.push(response.data.page.dataList[i]); } _this.sx=true; _this.xl=true; if (response.data.page.totalPage == _this.pageNo) { _this.is = false; _this.context="暂无更多数据"; } //_this.ContractList = response.data.page.dataList; }) .catch(function(error) { // 发生错误 }); } else { //document.getElementById("nodata").style.display = "block"; } }, select() { this.$router.replace({ name: "select", params: { user: this.user, departCode:this.departCode, zqCode:this.zqCode, xzCode:this.xzCode, zqName:this.zqName, presser:this.presser } }); }, jumppage(val) { this.$router.replace({name: "contractInfo", params: { user: this.user,dictid: val, departCode:this.departCode, zqCode:this.zqCode, xzCode:this.xzCode, zqName:this.zqName, presser:this.presser}}); }, toIndex(){ this.$router.replace({name: "index"+this.user.wxUserInfo.userType, params: { user: this.user}}); } } }; </script> <style> .pr-wrap_tra { display: flex; height: calc(93vh); justify-content: center; width: 100%; } .pr-wrap_tra .wrap-part_tra { height: 100%; width: 100%; } .pr-wrap_tra .wrap-part_tra .first_tra { width: 100%; width: 100%; } .contractList_css_tra { position: relative; margin: 0 auto; width: 90%; height: 170px; background-color: #ffffff; border-radius: 5px; padding: 10px 10px 10px 10px; box-shadow: 5px 5px 10px 2px#DCDCDC; margin-bottom: 20px; } .tr_css_tra { margin: 10px 10px 10px 10px; /* border: 1px solid red; */ } /* .table_tra { width: 100%; text-align: center; margin-top: 50px; position: relative; margin: 0 auto; } */ .content_tra { color: #045ce4; } .table_css_tra{ width: 100%; text-align: center; margin-top: 50px; position: relative; margin: 0 auto; } </style> ```
linux上导入1个G的dmp,导出来只有不到5M
在centos7的oracle上创建新用户后,导入了一个1G多的dmp文件,再将这个用户导出时只有几个M ``` [oracle@oracle-test ~]$ export NLS_LANG=AMERICAN_AMERICA.ZHS16GBK[oracle@oracle-test ~]$ exp isc/isc@192.168.157.132:1521/orcl file=/disk3/expisc/tisc.dmp owner=isc Export: Release 11.2.0.1.0 - Production on Tue Jan 14 12:36:23 2020 Copyright (c) 1982, 2009, Oracle and/or its affiliates. All rights reserved. Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production With the Partitioning, OLAP, Data Mining and Real Application Testing options Export done in ZHS16GBK character set and AL16UTF16 NCHAR character set About to export specified users ... . exporting pre-schema procedural objects and actions . exporting foreign function library names for user ISC . exporting PUBLIC type synonyms . exporting private type synonyms . exporting object type definitions for user ISC About to export ISC's objects ... . exporting database links . exporting sequence numbers . exporting cluster definitions . about to export ISC's tables via Conventional Path ... . . exporting table HR_ORG_BASIC_INFO 0 rows exported . . exporting table HR_ORG_BASIC_INFO_TEMP 0 rows exported . . exporting table HR_POST_BASIC_INFO 0 rows exported . . exporting table HR_USER_BASIC_INFO 0 rows exported . . exporting table ISC_ACCOUNT 4 rows exported . . exporting table ISC_ACCOUNT_EXT_PROP 0 rows exported . . exporting table ISC_ACTOR_ROLE_R 4362 rows exported . . exporting table ISC_APPLICATION 3 rows exported . . exporting table ISC_APPSHOW_CONF 1 rows exported . . exporting table ISC_APP_CODE_CONF 0 rows exported . . exporting table ISC_APP_CODE_FIELD_EXT 0 rows exported . . exporting table ISC_APP_DATARESOUCE_R 3 rows exported . . exporting table ISC_AUTHORIZE_COMMIT 0 rows exported . . exporting table ISC_BASEORG 8801 rows exported . . exporting table ISC_BASEORG_EXT_PROP 0 rows exported . . exporting table ISC_BASEORG_SPORG_UNIT_R 0 rows exported . . exporting table ISC_COMMON_CONST 196 rows exported . . exporting table ISC_DEPLOY 2 rows exported . . exporting table ISC_DIM 0 rows exported . . exporting table ISC_DUTY 0 rows exported . . exporting table ISC_LOGIN_LOCK 36 rows exported . . exporting table ISC_MAIL_CONF 0 rows exported . . exporting table ISC_MAIL_TEMPLATE_CONF 0 rows exported . . exporting table ISC_MDMORG_SPORG_UNIT_R 0 rows exported . . exporting table ISC_MDM_ORG 0 rows exported . . exporting table ISC_MSG_RESOURCE 0 rows exported . . exporting table ISC_NODE 3 rows exported . . exporting table ISC_NODE_DEPLOY_R 2 rows exported . . exporting table ISC_ORG_ATTRIBUTE 11 rows exported . . exporting table ISC_ORG_SYS_DIM_R 0 rows exported . . exporting table ISC_ORG_UNIT_DIM_R 0 rows exported . . exporting table ISC_RESOURCE 642 rows exported . . exporting table ISC_RESOURCE_EXT_PROPERTY 172 rows exported . . exporting table ISC_RESOURCE_EXT_PROPERTY_ETL 0 rows exported . . exporting table ISC_RESOURCE_TYPE 15 rows exported . . exporting table ISC_RESOURC_TYPE_APPLICATION_R 0 rows exported . . exporting table ISC_RES_EXT_VALUE 3230 rows exported . . exporting table ISC_RES_RES_R 638 rows exported . . exporting table ISC_ROLEGROUP 8 rows exported . . exporting table ISC_ROLE_LAYER_BY_ORG 67 rows exported . . exporting table ISC_ROLE_RES_R 2947 rows exported . . exporting table ISC_SECURE_CONF 2 rows exported . . exporting table ISC_SPECIALORG_UNIT 9 rows exported . . exporting table ISC_SPECIALORG_UNIT_BAK 0 rows exported . . exporting table ISC_SPORG_EXTPROP 0 rows exported . . exporting table ISC_SPORG_EXTPROPVAL 0 rows exported . . exporting table ISC_SPORG_EXTPROP_ATTR_R 0 rows exported . . exporting table ISC_SPROLE 81 rows exported . . exporting table ISC_SPROLE_EXT 0 rows exported . . exporting table ISC_SPROLE_EXT_VALUE 0 rows exported . . exporting table ISC_SPROLE_R 0 rows exported . . exporting table ISC_SP_DOMAIN 3 rows exported . . exporting table ISC_SP_DOMAIN_CODE_RELATION 15 rows exported . . exporting table ISC_SP_ORG_SYSTEM 3 rows exported . . exporting table ISC_STRATEGY_BASEORG_R 0 rows exported . . exporting table ISC_STRATEGY_CONF 0 rows exported . . exporting table ISC_STRATEGY_SESSION 0 rows exported . . exporting table ISC_STRATEGY_USER 0 rows exported . . exporting table ISC_SYNC_LOG 0 rows exported . . exporting table ISC_SYNC_PROCESS 0 rows exported . . exporting table ISC_SYSTEM_START_CONFIG 1 rows exported . . exporting table ISC_TEMP_ACTOR_ROLE_TBL 0 rows exported . . exporting table ISC_TEMP_USER 0 rows exported . . exporting table ISC_TEMP_USER_TBL 0 rows exported . . exporting table ISC_UNIT 27 rows exported . . exporting table ISC_USER 1947 rows exported . . exporting table ISC_USER_CFCA_CONN 0 rows exported . . exporting table ISC_USER_DUTY 0 rows exported . . exporting table ISC_USER_EXT 0 rows exported . . exporting table ISC_USER_EXT_PROPERTY 0 rows exported . . exporting table ISC_USER_EXT_PROP_ERP 0 rows exported . . exporting table ISC_USER_EXT_PROP_VALUE_ERP 0 rows exported . . exporting table ISC_USER_PASSWORDUSEFULDAY 54 rows exported . . exporting table ISC_USER_PASSWORD_REPETITIONS 20 rows exported . . exporting table ISC_USER_SPORG 1557 rows exported . . exporting table ISC_WO_ACCOUNTAPPLY 0 rows exported . . exporting table ISC_WO_ACCOUNT_CHANGE 0 rows exported . . exporting table ISC_WO_APPCONF_CHANGE 0 rows exported . . exporting table ISC_WO_APPROVAL_COMMENTS 0 rows exported . . exporting table ISC_WO_APP_REGISTER 0 rows exported . . exporting table ISC_WO_ORDER 0 rows exported . . exporting table ISC_WO_ROLELIST 0 rows exported . . exporting table ISC_WO_ROLES 0 rows exported . . exporting table OPERATE_OBJ 81 rows exported . . exporting table OPERATE_TYPE 419 rows exported . . exporting table RESOURCE_DEFAULT_PROPERTY 43 rows exported . . exporting table SAS_REPORT_FILES_LOG 0 rows exported . . exporting table SAS_STANDARD_DB_LOG_201301 0 rows exported . . exporting table SAS_STANDARD_LOG_TYPE 5 rows exported . . exporting table SAS_STATISTICAL_RULES 0 rows exported . . exporting table SAS_STATISTICS_DAY_LOGIN_COUNT 44 rows exported . . exporting table SAS_STATISTICS_DAY_LOGIN_USERS 53 rows exported . . exporting table SAS_STATISTICS_SP_VISIT_COUNT 1 rows exported . . exporting table USER_VERIFY 6 rows exported . exporting synonyms . exporting views . exporting stored procedures . exporting operators . exporting referential integrity constraints . exporting triggers . exporting indextypes . exporting bitmap, functional and extensible indexes . exporting posttables actions . exporting materialized views . exporting snapshot logs . exporting job queues . exporting refresh groups and children . exporting dimensions . exporting post-schema procedural objects and actions . exporting statistics Export terminated successfully without warnings. ``` 请问为什么会这样子?
IE 8中jquery file upload 上传图片没反应
jquery file upload 组件在chrome中好使 在IE中愣是没反应,前台的请求发送不到后台Controller中 后台SpringMVC 接受请求如下 @RequestMapping(value = "/fileupload", method = RequestMethod.POST) public @ResponseBody HBaseFileInfo upload(HttpServletRequest request, HttpServletResponse response) throws IOException {……} 前台 $('#fileupload').fileupload({ url: url, autoUpload: true, dataType: 'json', acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/, done: function (e, data) { $.each(data.files, function (index, file) { $("#newfiles").append(file.preview); }); $('#progress .bar').css('width','0%'); }, progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .bar').css( 'width', progress + '%' ); } }); 搞了一天,都要搞死了。。。有人遇到过类似问题不
jquery.fileupload.js 上传插件进度条的问题
jquery.fileupload.js上传,为何在页面中上传完成之后才执行progressall。 是后端程序要返回进度吗?怎么弄呢 环境: mvc 代码: $("#" + FileID).fileupload({ url: DocumentHost + UploadFile, dataType: 'text', type: "POST", formData: { }, forceIframeTransport: true, //跨域支持 autoUpload: false, done: function (e, data) {}, add: function (e, data) {}, change: function (e, data) {}, progress: function (e, data) {//设置上传进度事件的回调函数 var progress = parseInt(data.loaded / data.total * 100, 10); $("#progress_" + FileID).css("width", parseInt(progress) + "%"); $("#complete_" + FileID).html(parseInt(progress) + "%"); }, progressall: function (e, data) {//设置上传进度事件的回调函数 var progress = parseInt(data.loaded / data.total * 100, 10); $("#progress_" + FileID).css("width", parseInt(progress) + "%"); $("#complete_" + FileID).html(parseInt(progress) + "%"); } });
谁能帮忙解读下下面的代码
$(function(){ var foo = function (options){ var self = this; self.options = $.extend({ parent: $("#myForm"), register: $("[node-type=register]"), submit: $("[node-type=submit]") }, options); self.bindEvent(); }; foo.prototype = { bindEvent: function (){ var self = this; self.register(); }, register: function (){ var self = this, parent = self.options.parent, register = self.options.register; register.on("click", function (){ var jqXML = $.ajax({ url: "/register", dataType: "json", type: "post", data: parent.serialize() }); jqXML.done(function (json){ if(json.code == 200){ alert(json.msg); }else{ alert(json.msg); } }); }); } }; new foo(); })
在插入一个新用户的时候一直显示网络错误
![图片说明](https://img-ask.csdn.net/upload/201906/21/1561105721_387160.png)这一段出错,是这个文件有问题吗![图片说明](https://img-ask.csdn.net/upload/201906/21/1561105870_774201.png) if(r.open(i.type,i.url,i.async,i.username,i.password),i.xhrFields)for(n in i.xhrFields)r[n]=i.xhrFields[n];for(n in i.mimeType&&r.overrideMimeType&&r.overrideMimeType(i.mimeType),i.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest"),e)r.setRequestHeader(n,e[n]);o=function(e){return function(){o&&(o=a=r.onload=r.onerror=r.onabort=r.ontimeout=r.onreadystatechange=null,"abort"===e?r.abort():"error"===e?"number"!=typeof r.status?t(0,"error"):t(r.status,r.statusText):t(Ut[r.status]||r.status,r.statusText,"text"!==(r.responseType||"text")||"string"!=typeof r.responseText?{binary:r.response}:{text:r.responseText},r.getAllResponseHeaders()))}},r.onload=o(),a=r.onerror=r.ontimeout=o("error"),void 0!==r.onabort?r.onabort=a:r.onreadystatechange=function(){4===r.readyState&&C.setTimeout(function(){o&&a()})},o=o("abort");try{r.send(i.hasContent&&i.data||null)}catch(e){if(o)throw e}},abort:function(){o&&o()}}}),k.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),k.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return k.globalEval(e),e}}}),k.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),k.ajaxTransport("script",function(n){var r,i;if(n.crossDomain||n.scriptAttrs)return{send:function(e,t){r=k("<script>").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Vt,Gt=[],Yt=/(=)\?(?=&|$)|\?\?/;k.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Gt.pop()||k.expando+"_"+kt++;return this[e]=!0,e}}),k.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Yt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Yt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Yt,"$1"+r):!1!==e.jsonp&&(e.url+=(St.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||k.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?k(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Gt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Vt=E.implementation.createHTMLDocument("").body).innerHTML="<form></form><form></form>",2===Vt.childNodes.length),k.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=D.exec(e))?[t.createElement(i[1])]:(i=we([e],t,o),o&&o.length&&k(o).remove(),k.merge([],i.childNodes)));var r,i,o},k.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1<s&&(r=mt(e.slice(s)),e=e.slice(0,s)),m(t)?(n=t,t=void 0):t&&"object"==typeof t&&(i="POST"),0<a.length&&k.ajax({url:e,type:i||"GET",dataType:"html",data:t}).done(function(e){o=arguments,a.html(r?k("<div>").append(k.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},k.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){k.fn[t]=function(e){return this.on(t,e)}}),k.expr.pseudos.animated=function(t){return k.grep(k.timers,function(e){return t===e.elem}).length},k.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=k.css(e,"position"),c=k(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=k.css(e,"top"),u=k.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,k.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},k.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){k.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===k.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===k.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=k(e).offset()).top+=k.css(e,"borderTopWidth",!0),i.left+=k.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-k.css(r,"marginTop",!0),left:t.left-i.left-k.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===k.css(e,"position"))e=e.offsetParent;return e||ie})}}),k.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;k.fn[t]=function(e){return _(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),k.each(["top","left"],function(e,n){k.cssHooks[n]=ze(y.pixelPosition,function(e,t){if(t)return t=_e(e,n),$e.test(t)?k(e).position()[n]+"px":t})}),k.each({Height:"height",Width:"width"},function(a,s){k.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){k.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return _(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?k.css(e,t,i):k.style(e,t,n,i)},s,n?e:void 0,n)}})}),k.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){k.fn[n]=function(e,t){return 0<arguments.length?this.on(n,null,e,t):this.trigger(n)}}),k.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),k.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}}),k.proxy=function(e,t){var n,r,i;if("string"==typeof t&&(n=e[t],t=e,e=n),m(e))return r=s.call(arguments,2),(i=function(){return e.apply(t||this,r.concat(s.call(arguments)))}).guid=e.guid=e.guid||k.guid++,i},k.holdReady=function(e){e?k.readyWait++:k.ready(!0)},k.isArray=Array.isArray,k.parseJSON=JSON.parse,k.nodeName=N,k.isFunction=m,k.isWindow=x,k.camelCase=V,k.type=w,k.now=Date.now,k.isNumeric=function(e){var t=k.type(e);return("number"===t||"string"===t)&&!isNaN(e-parseFloat(e))},"function"==typeof define&&define.amd&&define("jquery",[],function(){return k});var Qt=C.jQuery,Jt=C.$;return k.noConflict=function(e){return C.$===k&&(C.$=Jt),e&&C.jQuery===k&&(C.jQuery=Qt),k},e||(C.jQuery=C.$=k),k}); $.ajax({ type: "post", url: getPath() + "/registerUser", async: false, dataType:'json', contentType: 'application/json', data:JSON.stringify({"id":0,"name":userName,"password":userPassword,"email":userEmail,"role":false}), success: function (data) { if (data.flag) { $('#userName').addClass('is-valid'); $('#userPassword').addClass('is-valid'); $('#userEmail').addClass('is-valid'); $('#userPasswordCheck').addClass('is-valid'); $('#registerResult').addClass('alert alert-success'); $('#registerResult').html('注册成功!跳转至<a href="login.html">登录</a>界面') setTimeout(window.location.href = 'login.html', 5000); } else { alert('注册失败'); } }, error: function () { alert("网络错误"); } }) }
ajax向后台请求数据并成功返回,但不执行success也不执行error
服务器端返回字符串类型的数据正常。前端代码如下: ``` $('#doc-vld-msg').validator({ submit: function () { var formValidity = this.isFormValid(); if (formValidity) { var progress = $.AMUI.progress; $.ajax({ type: "POST", url: "save.ashx", cache: "false", dataType: "text", data: { BicycleID: $("#doc-vld-name-2-1").val(), University: $("#doc-select-1-1").val(), Password: $("#doc-vld-age-2-1").val(), }, beforeSend: function () { progress.start(); }, success: function (result) { alert(result); window.location.href = "index.html"; }, error: function (jqXHR) { alert("发生错误:" + jqXHR.status); }, complete: function () { progress.done(); } }); } else { alert("未完成验证!"); } } }); ``` 先是做一个前台控件的验证,验证通过就发送ajax请求,我在浏览器和后台都看过是OK 200,但就是不执行success,也不执行error,我试了好多办法,发现,在if最后加一个alert()就可以执行success或者error了,代码如下: ``` $('#doc-vld-msg').validator({ submit: function () { var formValidity = this.isFormValid(); if (formValidity) { var progress = $.AMUI.progress; $.ajax({ type: "POST", url: "save.ashx", cache: "false", dataType: "text", data: { BicycleID: $("#doc-vld-name-2-1").val(), University: $("#doc-select-1-1").val(), Password: $("#doc-vld-age-2-1").val(), Random: getRandom(1000) }, beforeSend: function () { progress.start(); }, success: function (result) { alert(result); window.location.href = "index.html"; }, error: function (jqXHR) { alert("发生错误:" + jqXHR.status); }, complete: function () { progress.done(); } }); alert("数据已提交,正在查询是否能成功...");//就是添加的这一句 } else { alert("未完成验证!"); } } }); ``` 但是问题来了,他是先执行alert("数据已提交,正在查询是否能成功...");再执行success或者error,这是为什么?然后还有为什么我不添加这一句就不执行呢? 大神们,这是什么原因?我是个菜鸟,望大神解答一下。
Js Ajax相同语法执行不同
下面三段js的ajax代码,都是传入username和password访问路径来获取请求,为什么只有第一段代码能正确获取到数据,但是第二段和第三段代码能访问到路径,但是返回的数据显示missing username /** 能正确获取数据的代码 */ var settings = { "url": "http://xxxxxxx/get_data.php?action=projectdata&project=test", "method":"POST", "headers":{ "Content-Type":"text/plain" }, "data":"{\"username\":\"xxxxx\",\"password\":\"xxxxx\"}" } $.ajax(settings).done(function (response) { console.log(response); }) /** 代码2 **/ $.ajax({ url:"http://xxxxxxx/get_data.php?action=projectdata&project=test", type:"POST", data: { "username": "xxxxxx", "password": "xxxxxx" }, dataType:'json', success: function (data) { console.log(data); }, error: function (err) { console.log(err); } }); /** 代码块 3 **/ var xhr = new XMLHttpRequest(); xhr.open("post","http://xxxxxxx/get_data.php?action=projectdata&project=test"); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded") var sender = "{\"username\":\"xxxxx\",\"password\":\"******\"}"; //var sender = {"username":"xxxxx","password":"xxxxx"}; xhr.send(sender); xhr.onreadystatechange = function () { // 这步为判断服务器是否正确响应 if (xhr.readyState == 4 && xhr.status == 200) { console.log(xhr.responseText); } }; 这三段代码有什么区别吗
php+mvc模式的登陆口验证码可以点击刷新,不会自动刷新,求大神解决
1:描述问题:网站首页登陆口不管如何刷新[F5],验证码都不会变。但是点击验证码的话可以变为新的验证码!而且我们使用验证码登陆成功后同时退出来,此时登陆口的验证码还是之前使用过的验证码,没有更新!请大神帮我解决下,贴出正确的代码!因为本人不是很懂,只会照葫芦画瓢!万分感谢!无解决方案的请别回复了谢谢! 文件名:PassportController 代码如下,这个应该是控制器 /* 生成验证码 */ public function verify() { $config = [ 'fontSize' => 19, // 验证码字体大小 'length' => 4, // 验证码位数 'imageH' => 34 ]; $Verify = new Verify($config); $Verify->entry(); } /* 验证码校验 */ public function check_verify($code, $id = '') { $verify = new \Think\Verify(); $res = $verify->check($code, $id); $this->ajaxReturn($res, 'json'); } public function accessRules() { return array( array('allow', // 允许所有用户访问 'login' 动作. 'users'=>array('*'), ), array('allow', // 允许认证用户访问所有动作 'users'=>array('@'), ), array('deny', // 拒绝所有的用户。 'users'=>array('*'), ), ); } /* 异地登录检测 */ public function actionPlaceOtherLogin() { if(isset($_POST['username']) && $_POST['username']!="" && isset($_POST['pwd']) && $_POST['pwd']) { $siteLogin=new SiteLoginForm; $siteLogin->username=$_POST['username']; $siteLogin->password=$_POST['pwd']; $siteLogin->verifyCode=$_POST['verifyCode']; $siteLogin->rememberMe=false; if($siteLogin->validate())//用户名密码正确 { $userinfo=User::model()->findByAttributes(array( 'Username'=>$_POST['username'], 'PassWord'=>md5($_POST['pwd']) )); if($userinfo->Status==0)//用户帐号没有被冻结,处于正常状态 { if($userinfo->PlaceOtherLogin==0)//用户没有开启异地登录,则允许用户直接提交登录 { echo "true"; }else//开启异地登录 { //1.检查此次登录的ip与最近一次登录的ip是否相同 $lastLoginLog=Loginlog::model()->find(array( 'condition'=>'userid='.$userinfo->id, 'order'=>'id desc' )); if($lastLoginLog->loginip===XUtils::getClientIP())//如果本次登录ip与最近一次登录ip相同则允许用户直接提交 { echo "true"; }else//如果不同则返回通知使用短信验证 { echo $userinfo->Phon;//需要手机接手短信验证码,返回手机号码,以便发送短信进行验证 } } }else//帐号被冻结 { echo "LOCK"; } }else { echo "FAIL"; } } } // 登陆口的文件名:index 代码如下 // <link rel="stylesheet" type="text/css" href="<?php echo VERSION2;?>2_files/index.css"> <div class="banNer"><!--首页幻灯--> <ul class="rslides" id="slider"> <li style="background: url(<?php echo VERSION2;?>img/banner/banner_tg.jpg) no-repeat center top;"> <li style="background: url(<?php echo VERSION2;?>img/banner/003.jpg) no-repeat center top;"> </li> </ul> <!--登录区域--> <div class="login_frame_bg" <?php if(Yii::app()->user->getId())echo 'style="display:none;"';?>> <div class="login_frame"> <span class="warningSpan"<?php if(isset($_GET['loginStatus']) && $_GET['loginStatus']=='fail') echo 'style="display:block;"';?>>用户名或密码错误</span> <div id="myForm"> <table> <form method="post" onsubmit="return checkLogin()" action="<?php echo $this->createUrl('passport/login');?>"> <tbody> <tr> <td> <div class="login_mailbox"> <input type="hidden" name="User[position]" value="index" /> <input id="lusername" type="text" name="User[Username]" autocomplete="off" placeholder="用户名"> </div> </td> </tr> <tr> <td> <p class="zq" id="miaoname" style="margin:-15px 0px 10px;"></p> </td> </tr> <tr> <td> <div class="login_ps"> <input id="lpassword" type="password" name="User[PassWord]" name="LoginForm[password]" placeholder="请输入密码"> </div> </td> </tr> <tr> <td> <table> <tr> <td> <input type="text" name="User[VerifyCode]" class="" placeholder="请输入右边验证码" style=" width: 170px; margin-right: 5px; border-radius: 5px; line-height: 35px; border: 1px solid #fff; padding-left: 5px;" id="verifyCode" /> </td> <td> <?php $this->widget( 'CCaptcha', array('showRefreshButton'=>false, 'clickableImage'=>true, 'imageOptions'=>array( 'alt'=>'点击换图', 'title'=>'点击换图', 'style'=>'cursor:pointer; background:#fff; height:27px; border-radius:5px;' ) ) ); ?> </td> </tr> </table> </td> </tr> <tr> <td> <p class="zq" style="height: 10px;"></p> </td> </tr> <tr> <td> <p id="miaopwd" class="zq" style="margin:-15px 0px 10px;"></p> </td> </tr> <tr> <td> <li style=" color:#fff; font-size:12px;"><input name="User[rememberMe]" type="checkbox" style="position: relative; top: 3px; width:12px;" /> 下次自动登录<a href="javascript:;" class="forgetPwd" style=" float:right; margin-right:28px; color:white;">忘记密码?</a></li><br /> </td> </tr> <tr> <td> <button class="login-btn" id="login_btn">登录</button> </td> </tr> <tr> <td> <span><a href="<?php echo $this->createUrl('passport/regist');?>" id="a">还没有账号?点击注册>></a></span> </td> </tr> </tbody> <form> </table> </div> </div> </div> <div class="indIntr" style="background="achose.png" ><!--系统优势--> <div class="why_main4 clearfix"> </div> </div> <script> //登录表单检测 function checkLogin() { if($("#lusername").val()=="") { layer.tips('用户名不能为空', '#lusername'); return false; }else if($("#lpassword").val()=="") { layer.tips('密码不能为空', '#lpassword'); return false; }else if($("#verifyCode").val()=="") { layer.tips('验证码不能为空', '#verifyCode'); return false; }else { var submitStatus=0;//提交状态初始化verifyCode var phone=0;//手机号码初始化 //检查是否开启异地登录 $.ajax({ type:"POST", url:"<?php echo $this->createUrl('passport/placeOtherLogin');?>", data:{ "username":$("#lusername").val(), "pwd":$("#lpassword").val(), "verifyCode":$("#verifyCode").val(), }, async:false, success:function(msg) { if(msg=="true")//不用检测 { submitStatus=1; }else if(msg=="FAIL")//用户名或密码不正确 { } else if(msg=="LOCK")//用户帐户被冻结 { submitStatus=3; }else//需要发送手机验证码 { phone=msg;//赋值用户手机号 submitStatus=2; } } }); /*alert(submitStatus); exit;*/ //检查是否开启异地登录 if(submitStatus==0)//用户名密码不正确 { layer.tips('用户名,密码或验证码不正确', '#lusername', { tips: [1, '#0FA6D8'] //还可配置颜色 }); return false; }else if(submitStatus==3) { //询问框 layer.confirm('<span style="color:red;">您的帐户已被冻结,如有需要请联系客服人员</span>', { btn: ['知道了'] //按钮 }); return false; }else if(submitStatus==1)//直接提交 { return true; }else//2表示需要发送短信验证码 { //发送验证码 $.ajax({ type:"POST", url:"<?php echo $this->createUrl('site/sms');?>", data:{"phone":phone,"phoneCode":"DONE"}, async:false, success:function(msgCode) { if(msgCode=="SUCCESS") { //询问框 layer.confirm('<span style="color:red;">短信发送成功(异地登录请输入手机验证码)</span><br/>验证码<input class="text1 phoneCodeVal" name="phoneCodeVal" />', { btn: ['确定提交'] //按钮 },function(){ if($(".phoneCodeVal").val()=="")//验证码不为空 { layer.tips('验证码不能为空', '.phoneCodeVal'); }else{ //发送手机号与验证码去验证正确性 $.ajax({ type:"POST", url:"<?php echo $this->createUrl('passport/userCheckPhoneAndCode');?>", data:{"phone":phone,"phoneCode":$(".phoneCodeVal").val()}, async:false, success:function(msgCertain) { if(msgCertain=="SUCCESS")//手机验证码检测通过 { //验证通过直接进行提交登录 $.ajax({ type:"POST", url:"<?php echo $this->createUrl('passport/codePassLogin');?>", data:{"username":$("#lusername").val(),"pwd":$("#lpassword").val()}, async:false, success:function(msglogin) { if(msglogin=="SUCCESS")//登录成功刷新当前页面 { location.reload(); //询问框 }else//登录异常刷新当前页面 { layer.confirm('<span style="color:red;">登录异常</span>,您可以联系客服人员', { btn: ['知道了'] //按钮 }); } } }); //验证通过直接进行提交登录 }else if(msgCertain=="CODEFAIL")//验证不正确 { layer.tips('验证码不正确', '.phoneCodeVal'); }else//手机号异常 { layer.tips('手机号码异常', '.phoneCodeVal'); } } }); //发送手机号与验证码去验证正确性 } }); }else { //询问框 layer.confirm('<span style="color:red;">异地登录验证-短信发送失败,可能发送次数过多</span>,您可以联系客服人员', { btn: ['知道了'] //按钮 }); phoneAndCodeCheckStatus=0; } } }); //发送短信验证码结束 return false; } } } //忘记密码 $(".forgetPwd").click(function(){ layer.open({ type: 2, title:'找回密码', area: ['375px','270px'], skin: 'layui-layer-rim', //加上边框 content: ['<?php echo $this->createUrl('passport/forgetPwd');?>', 'no'] }); }); </script> // 能帮我解决问题的才回复,或者还需要我提供什么的请留言,谢谢了,
asp.net webuploader多图片上传并保存文件路径到数据库
![图片说明](https://img-ask.csdn.net/upload/201906/22/1561187942_114655.jpg) 要做一个滚动窗功能,使用webuploader插件 不知道在哪获取文件路径,保存到数据库里 上传的upload.js ``` (function( $ ){ // 当domReady的时候开始初始化 $(function() { var $wrap = $('.uploader-list-container'), // 图片容器 $queue = $( '<ul class="filelist"></ul>' ) .appendTo( $wrap.find( '.queueList' ) ), // 状态栏,包括进度和控制按钮 $statusBar = $wrap.find( '.statusBar' ), // 文件总体选择信息。 $info = $statusBar.find( '.info' ), // 上传按钮 $upload = $wrap.find( '.uploadBtn' ), // 没选择文件之前的内容。 $placeHolder = $wrap.find( '.placeholder' ), $progress = $statusBar.find( '.progress' ).hide(), // 添加的文件数量 fileCount = 0, // 添加的文件总大小 fileSize = 0, // 优化retina, 在retina下这个值是2 ratio = window.devicePixelRatio || 1, // 缩略图大小 thumbnailWidth = 110 * ratio, thumbnailHeight = 110 * ratio, // 可能有pedding, ready, uploading, confirm, done. state = 'pedding', // 所有文件的进度信息,key为file id percentages = {}, // 判断浏览器是否支持图片的base64 isSupportBase64 = ( function() { var data = new Image(); var support = true; data.onload = data.onerror = function() { if( this.width != 1 || this.height != 1 ) { support = false; } } data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; return support; } )(), // 检测是否已经安装flash,检测flash的版本 flashVersion = ( function() { var version; try { version = navigator.plugins[ 'Shockwave Flash' ]; version = version.description; } catch ( ex ) { try { version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash') .GetVariable('$version'); } catch ( ex2 ) { version = '0.0'; } } version = version.match( /\d+/g ); return parseFloat( version[ 0 ] + '.' + version[ 1 ], 10 ); } )(), supportTransition = (function(){ var s = document.createElement('p').style, r = 'transition' in s || 'WebkitTransition' in s || 'MozTransition' in s || 'msTransition' in s || 'OTransition' in s; s = null; return r; })(), // WebUploader实例 uploader; if ( !WebUploader.Uploader.support('flash') && WebUploader.browser.ie ) { // flash 安装了但是版本过低。 if (flashVersion) { (function(container) { window['expressinstallcallback'] = function( state ) { switch(state) { case 'Download.Cancelled': alert('您取消了更新!') break; case 'Download.Failed': alert('安装失败') break; default: alert('安装已成功,请刷新!'); break; } delete window['expressinstallcallback']; }; var swf = 'expressInstall.swf'; // insert flash object var html = '<object type="application/' + 'x-shockwave-flash" data="' + swf + '" '; if (WebUploader.browser.ie) { html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '; } html += 'width="100%" height="100%" style="outline:0">' + '<param name="movie" value="' + swf + '" />' + '<param name="wmode" value="transparent" />' + '<param name="allowscriptaccess" value="always" />' + '</object>'; container.html(html); })($wrap); // 压根就没有安转。 } else { $wrap.html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>'); } return; } else if (!WebUploader.Uploader.support()) { alert( 'Web Uploader 不支持您的浏览器!'); return; } // 实例化 uploader = WebUploader.create({ pick: { id: '#filePicker-2', label: '点击选择图片' }, formData: { uid: 123 }, dnd: '#dndArea', paste: '#uploader', swf: '../Uploader.swf', chunked: false, chunkSize: 512 * 1024, server: './Ajax/UpLoad.ashx', // runtimeOrder: 'flash', accept: { title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' }, // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候,把图片打开。 disableGlobalDnd: true, fileNumLimit: 300, fileSizeLimit: 200 * 1024 * 1024, // 200 M fileSingleSizeLimit: 50 * 1024 * 1024 // 50 M }); // 拖拽时不接受 js, txt 文件。 uploader.on( 'dndAccept', function( items ) { var denied = false, len = items.length, i = 0, // 修改js类型 unAllowed = 'text/plain;application/javascript '; for ( ; i < len; i++ ) { // 如果在列表里面 if ( ~unAllowed.indexOf( items[ i ].type ) ) { denied = true; break; } } return !denied; }); uploader.on('dialogOpen', function() { console.log('here'); }); // uploader.on('filesQueued', function() { // uploader.sort(function( a, b ) { // if ( a.name < b.name ) // return -1; // if ( a.name > b.name ) // return 1; // return 0; // }); // }); // 添加“添加文件”的按钮, uploader.addButton({ id: '#filePicker2', label: '继续添加' }); uploader.on('ready', function() { window.uploader = uploader; }); // 当有文件添加进来时执行,负责view的创建 function addFile(file) { alert(file.name); var $li = $( '<li id="' + file.id + '">' + '<p class="title">' + file.name + '</p>' + '<p class="imgWrap"></p>'+ '<p class="progress"><span></span></p>' + '</li>' ), $btns = $('<div class="file-panel">' + '<span class="cancel">删除</span>' + '<span class="rotateRight">向右旋转</span>' + '<span class="rotateLeft">向左旋转</span></div>').appendTo( $li ), $prgress = $li.find('p.progress span'), $wrap = $li.find( 'p.imgWrap' ), $info = $('<p class="error"></p>'), showError = function( code ) { switch( code ) { case 'exceed_size': text = '文件大小超出'; break; case 'interrupt': text = '上传暂停'; break; default: text = '上传失败,请重试'; break; } $info.text( text ).appendTo( $li ); }; if ( file.getStatus() === 'invalid' ) { showError( file.statusText ); } else { // @todo lazyload $wrap.text( '预览中' ); uploader.makeThumb( file, function( error, src ) { var img; if ( error ) { $wrap.text( '不能预览' ); return; } if( isSupportBase64 ) { img = $('<img src="'+src+'">'); $wrap.empty().append( img ); } else { $.ajax('../server/preview.php', { method: 'POST', data: src, dataType:'json' }).done(function( response ) { if (response.result) { img = $('<img src="'+response.result+'">'); $wrap.empty().append( img ); } else { $wrap.text("预览出错"); } }); } }, thumbnailWidth, thumbnailHeight ); percentages[ file.id ] = [ file.size, 0 ]; file.rotation = 0; } file.on('statuschange', function( cur, prev ) { if ( prev === 'progress' ) { $prgress.hide().width(0); } else if ( prev === 'queued' ) { $li.off( 'mouseenter mouseleave' ); $btns.remove(); } // 成功 if ( cur === 'error' || cur === 'invalid' ) { console.log( file.statusText ); showError( file.statusText ); percentages[ file.id ][ 1 ] = 1; } else if ( cur === 'interrupt' ) { showError( 'interrupt' ); } else if ( cur === 'queued' ) { percentages[ file.id ][ 1 ] = 0; } else if ( cur === 'progress' ) { $info.remove(); $prgress.css('display', 'block'); } else if ( cur === 'complete' ) { $li.append( '<span class="success"></span>' ); } $li.removeClass( 'state-' + prev ).addClass( 'state-' + cur ); }); $li.on( 'mouseenter', function() { $btns.stop().animate({height: 30}); }); $li.on( 'mouseleave', function() { $btns.stop().animate({height: 0}); }); $btns.on( 'click', 'span', function() { var index = $(this).index(), deg; switch ( index ) { case 0: uploader.removeFile( file ); return; case 1: file.rotation += 90; break; case 2: file.rotation -= 90; break; } if ( supportTransition ) { deg = 'rotate(' + file.rotation + 'deg)'; $wrap.css({ '-webkit-transform': deg, '-mos-transform': deg, '-o-transform': deg, 'transform': deg }); } else { $wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')'); // use jquery animate to rotation // $({ // rotation: rotation // }).animate({ // rotation: file.rotation // }, { // easing: 'linear', // step: function( now ) { // now = now * Math.PI / 180; // var cos = Math.cos( now ), // sin = Math.sin( now ); // $wrap.css( 'filter', "progid:DXImageTransform.Microsoft.Matrix(M11=" + cos + ",M12=" + (-sin) + ",M21=" + sin + ",M22=" + cos + ",SizingMethod='auto expand')"); // } // }); } }); $li.appendTo( $queue ); } // 负责view的销毁 function removeFile( file ) { var $li = $('#'+file.id); delete percentages[ file.id ]; updateTotalProgress(); $li.off().find('.file-panel').off().end().remove(); } function updateTotalProgress() { var loaded = 0, total = 0, spans = $progress.children(), percent; $.each( percentages, function( k, v ) { total += v[ 0 ]; loaded += v[ 0 ] * v[ 1 ]; } ); percent = total ? loaded / total : 0; spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' ); spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' ); updateStatus(); } function updateStatus() { var text = '', stats; if ( state === 'ready' ) { text = '选中' + fileCount + '张图片,共' + WebUploader.formatSize( fileSize ) + '。'; } else if ( state === 'confirm' ) { stats = uploader.getStats(); if ( stats.uploadFailNum ) { text = '已成功上传' + stats.successNum+ '张照片至XX相册,'+ stats.uploadFailNum + '张照片上传失败,<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>' } } else { stats = uploader.getStats(); text = '共' + fileCount + '张(' + WebUploader.formatSize( fileSize ) + '),已上传' + stats.successNum + '张'; if ( stats.uploadFailNum ) { text += ',失败' + stats.uploadFailNum + '张'; } } $info.html( text ); } function setState( val ) { var file, stats; if ( val === state ) { return; } $upload.removeClass( 'state-' + state ); $upload.addClass( 'state-' + val ); state = val; switch ( state ) { case 'pedding': $placeHolder.removeClass( 'element-invisible' ); $queue.hide(); $statusBar.addClass( 'element-invisible' ); uploader.refresh(); break; case 'ready': $placeHolder.addClass( 'element-invisible' ); $( '#filePicker2' ).removeClass( 'element-invisible'); $queue.show(); $statusBar.removeClass('element-invisible'); uploader.refresh(); break; case 'uploading': $( '#filePicker2' ).addClass( 'element-invisible' ); $progress.show(); $upload.text( '暂停上传' ); break; case 'paused': $progress.show(); $upload.text( '继续上传' ); break; case 'confirm': $progress.hide(); $( '#filePicker2' ).removeClass( 'element-invisible' ); $upload.text( '开始上传' ); stats = uploader.getStats(); if ( stats.successNum && !stats.uploadFailNum ) { setState( 'finish' ); return; } break; case 'finish': stats = uploader.getStats(); if ( stats.successNum ) { alert( '上传成功' ); } else { // 没有成功的图片,重设 state = 'done'; location.reload(); } break; } updateStatus(); } uploader.onUploadProgress = function( file, percentage ) { var $li = $('#'+file.id), $percent = $li.find('.progress span'); $percent.css( 'width', percentage * 100 + '%' ); percentages[ file.id ][ 1 ] = percentage; updateTotalProgress(); }; uploader.onFileQueued = function( file ) { fileCount++; fileSize += file.size; if ( fileCount === 1 ) { $placeHolder.addClass( 'element-invisible' ); $statusBar.show(); } addFile( file ); setState( 'ready' ); updateTotalProgress(); }; uploader.onFileDequeued = function( file ) { fileCount--; fileSize -= file.size; if ( !fileCount ) { setState( 'pedding' ); } removeFile( file ); updateTotalProgress(); }; uploader.on( 'all', function( type ) { var stats; switch( type ) { case 'uploadFinished': setState( 'confirm' ); break; case 'startUpload': setState( 'uploading' ); break; case 'stopUpload': setState( 'paused' ); break; } }); uploader.onError = function( code ) { alert( 'Eroor: ' + code ); }; $upload.on('click', function() { if ( $(this).hasClass( 'disabled' ) ) { return false; } if ( state === 'ready' ) { uploader.upload(); } else if ( state === 'paused' ) { uploader.upload(); } else if ( state === 'uploading' ) { uploader.stop(); } }); $info.on( 'click', '.retry', function() { uploader.retry(); } ); $info.on( 'click', '.ignore', function() { alert( 'todo' ); } ); $upload.addClass( 'state-' + state ); updateTotalProgress(); }); })( jQuery ); ``` ashx文件 ``` <%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; using System.IO; using System.Text; public class Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //指定字符集 context.Response.ContentEncoding = System.Text.Encoding.UTF8; if (context.Request["REQUEST_METHOD"] == "OPTIONS") { context.Response.End(); } SaveFile(); } /// <summary> /// 文件保存操作 /// </summary> /// <param name="basePath"></param> private void SaveFile(string basePath = "~/Upload/Images/") { var name = string.Empty; basePath = (basePath.IndexOf("~") > -1) ? System.Web.HttpContext.Current.Server.MapPath(basePath) : basePath; // basePath = FileHelper.GetUploadPath(); HttpFileCollection files = System.Web.HttpContext.Current.Request.Files; //如果目录不存在,则创建目录 if (!Directory.Exists(basePath)) { Directory.CreateDirectory(basePath); } var suffix = files[0].ContentType.Split('/'); //获取文件格式 var _suffix = suffix[1].Equals("jpeg", StringComparison.CurrentCultureIgnoreCase) ? ".jpg" : suffix[1]; var _temp = System.Web.HttpContext.Current.Request["name"]; //如果不修改文件名,则创建随机文件名 //if (!string.IsNullOrEmpty(_temp)) //{ // name = _temp; //} //else //{ Random rand = new Random(24 * (int)DateTime.Now.Ticks); name = rand.Next() + "." + _suffix; //} //文件保存 var full = basePath + name; files[0].SaveAs(full); var _result = "{\"jsonrpc\" : \"2.0\", \"result\" : null, \"Imgurl\" : \"" + name + "\"}"; System.Web.HttpContext.Current.Response.Write(_result); } public bool IsReusable { get { return false; } } } ```
从 PHP MySQL 中检索数据然后传到视图列表中
我想从 PHP MySQL 中检索一个数据,然后传到试图列表中。我使用的下面的代码,但是还是没把数据放到 List View 中,如何改这个问题。 贴出我的代码,大家看看是哪儿出错了。 Activity Codes public class View extends Activity{ // Progress Dialog // Creating JSON Parser object JSONParser jParser = new JSONParser(); ArrayList<HashMap<String, String>> productsList; // url to get all products list private static String url_all_products = "http://atlantis-us.com/viewFile.php"; // JSON Node names private static final String TAG_NAME = "name"; ListView lv; // products JSONArray JSONArray products = null; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.all_products); // Get listview lv = (ListView) findViewById(R.id.list); // Hashmap for ListView productsList = new ArrayList<HashMap<String, String>>(); new LoadAllProducts().execute(); } class LoadAllProducts extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params); Log.d("All Products: ", json.toString()); ListAdapter adapter = new SimpleAdapter( View.this, productsList, R.layout.list_item, new String[] { TAG_NAME}, new int[] {R.id.name }); // updating listview lv.setAdapter(adapter); return null; } } } JSONParser Class public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) { // Making HTTP request try { // check for request method if(method == "POST"){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if(method == "GET"){ // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } log cat 10-26 14:57:53.673: I/Choreographer(1391): Skipped 61 frames! The application may be doing too much work on its main thread. 10-26 14:57:54.653: D/All Products:(1391): {"products":[{"name":"Ghalia"},{"name":"yuan"},{"name":"kevin"},{"name":"kevin"},{"name":"kevin"},{"name":"Ghalia"},{"name":"Ghalia"},{"name":"dbgg"},{"name":"Ghalia"},{"name":"Ghalia"},{"name":"test"}]} 10-26 14:57:54.663: W/dalvikvm(1391): threadid=11: thread exiting with uncaught exception (group=0x40a13300) 10-26 14:57:54.684: E/AndroidRuntime(1391): FATAL EXCEPTION: AsyncTask #1 10-26 14:57:54.684: E/AndroidRuntime(1391): java.lang.RuntimeException: An error occured while executing doInBackground() 10-26 14:57:54.684: E/AndroidRuntime(1391): at android.os.AsyncTask$3.done(AsyncTask.java:299) 10-26 14:57:54.684: E/AndroidRuntime(1391): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 10-26 14:57:54.684: E/AndroidRuntime(1391): at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 10-26 14:57:54.684: E/AndroidRuntime(1391): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 10-26 14:57:54.684: E/AndroidRuntime(1391): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 10-26 14:57:54.684: E/AndroidRuntime(1391): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 10-26 14:57:54.684: E/AndroidRuntime(1391): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 10-26 14:57:54.684: E/AndroidRuntime(1391): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 10-26 14:57:54.684: E/AndroidRuntime(1391): at java.lang.Thread.run(Thread.java:856) 10-26 14:57:54.684: E/AndroidRuntime(1391): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 10-26 14:57:54.684: E/AndroidRuntime(1391): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4607) 10-26 14:57:54.684: E/AndroidRuntime(1391): at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:835) 10-26 14:57:54.684: E/AndroidRuntime(1391): at android.view.View.requestLayout(View.java:15129) 10-26 14:57:54.684: E/AndroidRuntime(1391): at android.view.View.requestLayout(View.java:15129) 10-26 14:57:54.684: E/AndroidRuntime(1391): at android.view.View.requestLayout(View.java:15129) 10-26 14:57:54.684: E/AndroidRuntime(1391): at android.view.View.requestLayout(View.java:15129) 10-26 14:57:54.684: E/AndroidRuntime(1391): at android.view.View.requestLayout(View.java:15129) 10-26 14:57:54.684: E/AndroidRuntime(1391): at android.widget.AbsListView.requestLayout(AbsListView.java:1928) 10-26 14:57:54.684: E/AndroidRuntime(1391): at android.widget.ListView.setAdapter(ListView.java:488) 10-26 14:57:54.684: E/AndroidRuntime(1391): at com.example.mysql.View$LoadAllProducts.doInBackground(View.java:74) 10-26 14:57:54.684: E/AndroidRuntime(1391): at com.example.mysql.View$LoadAllProducts.doInBackground(View.java:1) 10-26 14:57:54.684: E/AndroidRuntime(1391): at android.os.AsyncTask$2.call(AsyncTask.java:287) 10-26 14:57:54.684: E/AndroidRuntime(1391): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 10-26 14:57:54.684: E/AndroidRuntime(1391): ... 5 more
XMLHttpRequest对象向服务器(servlet)发出请求,服务端如何接收
/** * 页面上显示需要上传的文件 * @private */ function _showUploadFile(file) { var reader = new FileReader(); console.log(file) // console.log(reader); //判断文件类型 if (file.type.match(/image*/)) { reader.onload = function (e) { var formData = new FormData(); console.info("1:"+formData); console.info(formData); var li = $("#template li").clone(); var img = li.find("img"); var progress = li.find(".progress"); var percentage = li.find(".percentage"); percentage.text("0%"); img.attr("src", e.target.result); $("ul", $(_uploadEle)).append(li); $(_uploadEle).find("li").size() == 10 && $(_uploadEle).width(($(_uploadEle).width() + 8) + "px").css("overflow", "auto"); console.info(file); //formData.uploadFile = file; formData.append("uploadFile", file); //上传文件到服务器 _uploadToServer(formData, li, progress, percentage); }; reader.readAsDataURL(file); } else { console.log("此" + file.name + "不是图片文件!"); } } /** * 上传文件到服务器 * @private */ function _uploadToServer(formData, li, progress, percentage) { var xhr = new XMLHttpRequest(); xhr.open("POST", "http://localhost:8080/html5Upload/FileUploadServlet.html", true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest', 'Content-Type', 'multipart/form-data;'); //HTML5新增的API,存储了上传过程中的信息 xhr.upload.onprogress = function (e) { var percent = 0; if (e.lengthComputable) { //更新页面显示效果 percent = 100 * e.loaded / e.total; progress.height(percent ); percentage.text(percent + "%"); percent >= 100 && li.addClass("done"); } }; xhr.send(formData); } ``` 注:xhr.send(content);--向服务器发出请求,如果采用异步方式,该方法会立即返回。content可以指定为null表示不发送数据,其内容可以是DOM对象,输入流或字符串。 ```
layUI流加载,点击筛选后数据没有渲染出来?
1、首先筛选是通过下面ajax追加数据的 $.ajax({ type:"post", url:"http://127.0.0.0:8080/api/data", dataType:'json',//text,json,html data: {"income_bands":income_bands, "stars":stars, "sexs":sexs, "min_ages":min_ages,"max_ages":max_ages, "min_kmh_scores":min_kmh_scores,"max_kmh_scores":max_kmh_scores, "min_zj_scores":min_zj_scores,"max_zj_scores":max_zj_scores},//需要向后台传的数据格式,start为字典的key值,即后台接受的数据id success:function(result){ var contents =""; $("#contents").empty();//先清空 for (var i=0;i<result.length;i++){ $("#contents").append("<li style=\"border-bottom:1px #f3f3f3 solid;\"><a href=\"http://www.htmlsucai.com/\"> "+result[i][0] +"</a></br><a style=\"color:#BFBFBF;\"">"+result[i][1] +"</a></br><a style=\"color:#BFBFBF;\">"+result[i][2] +"</a></br><a style=\"color:#BFBFBF;\">"+result[i][3] +"</a></br><a style=\"color:#BFBFBF;\">"+result[i][4]+"</a></li>"); }; }, error:function(result){ alert("未查询到数据."); } 2、然后用另一个ajax进行数据流加载: <script> var pageSize = 10; var pageIndex = 0; layui.use('flow', function () { var $ = layui.jquery; var flow = layui.flow; flow.load({ elem: '#contents',//存放每条数据的容器 done: function (pageIndex, next) { //到达临界点(默认滚动触发),触发下一页 var lis = []; //以jQuery的Ajax请求为例,请求下一页数据(注意:page是从2开始返回) $.ajax({ type: "POST", url: "http://127.0.0.0:8080/api/all_data_page", dataType:'json',//text,json,html data: { "income_bands":income_bands, "stars":stars, "sexs":sexs, "min_ages":min_ages,"max_ages":max_ages, "min_kmh_scores":min_kmh_scores,"max_kmh_scores":max_kmh_scores, "min_zj_scores":min_zj_scores,"max_zj_scores":max_zj_scores, pageSize: pageSize, pageIndex: pageIndex }, success: function (data) { pageIndex = data[1][0]; //服务端返回的json字符必须包含pageIndex和pageCount属性,pageIndex表示页码,pageCount是总页数 for (var i = 0; i < data[0].length; i++) { var d = "<li style=\"border-bottom:1px #f3f3f3 solid;\"><a href=\"http://www.htmlsucai.com/\">"+data[0][i][0] +"</a></br><a style=\"color:#BFBFBF;\">"+data[0][i][1] +"</a></br><a style=\"color:#BFBFBF;\">"+data[0][i][2] +"</a></br><a style=\"color:#BFBFBF;\">">"+data[0][i][3] +"</a></br><a style=\"color:#BFBFBF;\">"+data[0][i][4]+"</a></li>"; lis.push(d);//每条数据都压入数组,LayUI会自动将每条信息插入Html的ID为#contents的元素 } **alert(lis.join(''))**; //执行下一页渲染,第二参数为:满足“加载更多”的条件,即后面仍有分页 //只有当前页小于总页数的情况下,才会继续出现加载更多 next(lis.join(''), pageIndex < data[1][1]); } }); } }); }); </script> 在上面可以看到数据是压缩进了lis里面了,但是没有被渲染出来,求助各位大神怎么解?????
restful请求index方法时,真正请求的是index_get的方法,请教下源代码这块逻辑在哪。
请求的域名是:cidemo.com/Admin/RestfulController/index/2 但是走的是 Admin模块下的RestfulController控制器中的index_get 得方法 RestfulController控制器中我继承了REST_Controller 但是在REST_Controller 中我没发现将index 变成 index_get的逻辑啊。有哪位大神帮忙解答下 处理逻辑的控制器文件: ``` <?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * Example * * This is an example of a few basic user interaction methods you could use * all done with a hardcoded array. * */ // This can be removed if you use __autoload() in config.php OR use Modular Extensions require APPPATH . '/libraries/REST_Controller.php'; class Restful extends REST_Controller { function index_get($id = '') { var_dump($id);die; // Example data for testing. $widgets = array( 1 => array('id' => 1, 'name' => 'sprocket'), 2 => array('id' => 2, 'name' => 'gear') ); if (!$id) { $id = $this->get('id'); } if (!$id) { //$widgets = $this->widgets_model->getWidgets(); if ($widgets) $this->response($widgets, 200); // 200 being the HTTP response code else $this->response(array('error' => 'Couldn\'t find any widgets!'), 404); } //$widget = $this->widgets_model->getWidget($id); $widget = @$widgets[$id]; // test code if ($widget) $this->response($widget, 200); // 200 being the HTTP response code else $this->response(array('error' => 'Widget could not be found'), 404); } function index_post() { $data = $this->_post_args; try { //$id = $this->widgets_model->createWidget($data); $id = 3; // test code //throw new Exception('Invalid request data', 400); // test code //throw new Exception('Widget already exists', 409); // test code } catch (Exception $e) { // Here the model can throw exceptions like the following: // * For invalid input data: new Exception('Invalid request data', 400) // * For a conflict when attempting to create, like a resubmit: new Exception('Widget already exists', 409) $this->response(array('error' => $e->getMessage()), $e->getCode()); } if ($id) { $widget = array('id' => $id, 'name' => $data['name']); // test code //$widget = $this->widgets_model->getWidget($id); $this->response($widget, 201); // 201 being the HTTP response code } else $this->response(array('error' => 'Widget could not be created'), 404); } public function index_put() { $data = $this->_put_args; try { //$id = $this->widgets_model->updateWidget($data); $id = $data['id']; // test code //throw new Exception('Invalid request data', 400); // test code } catch (Exception $e) { // Here the model can throw exceptions like the following: // * For invalid input data: new Exception('Invalid request data', 400) // * For a conflict when attempting to create, like a resubmit: new Exception('Widget already exists', 409) $this->response(array('error' => $e->getMessage()), $e->getCode()); } if ($id) { $widget = array('id' => $data['id'], 'name' => $data['name']); // test code //$widget = $this->widgets_model->getWidget($id); $this->response($widget, 200); // 200 being the HTTP response code } else $this->response(array('error' => 'Widget could not be found'), 404); } function index_delete($id = '') { // Example data for testing. $widgets = array( 1 => array('id' => 1, 'name' => 'sprocket'), 2 => array('id' => 2, 'name' => 'gear'), 3 => array('id' => 3, 'name' => 'nut') ); if (!$id) { $id = $this->get('id'); } if (!$id) { $this->response(array('error' => 'An ID must be supplied to delete a widget'), 400); } //$widget = $this->widgets_model->getWidget($id); $widget = @$widgets[$id]; // test code if ($widget) { try { //$this->widgets_model->deleteWidget($id); //throw new Exception('Forbidden', 403); // test code } catch (Exception $e) { // Here the model can throw exceptions like the following: // * Client is not authorized: new Exception('Forbidden', 403) $this->response(array('error' => $e->getMessage()), $e->getCode()); } $this->response($widget, 200); // 200 being the HTTP response code } else $this->response(array('error' => 'Widget could not be found'), 404); } public function response($info) { if (is_array($info)) { echo json_encode($info); } } public function index(){ echo "this is index methods"; } } ``` 继承的restful类文件: ``` <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class REST_Controller extends CI_Controller { private $method; private $format; private $get_args; private $put_args; private $args; // List all supported methods, the first will be the default format private $supported_formats = array( 'xml' => 'application/xml', 'json' => 'application/json', 'serialize' => 'text/plain', 'php' => 'text/plain', 'html' => 'text/html', 'csv' => 'application/csv' ); // Constructor function function __construct() { parent::__construct(); // How is this request being made? POST, DELETE, GET, PUT? $this->method = $this->_detect_method(); // Lets grab the config and get ready to party $this->load->config('rest'); if($this->config->item('rest_auth') == 'basic') { echo "basic"; $this->_prepareBasicAuth(); } elseif($this->config->item('rest_auth') == 'digest') { echo "digest"; $this->_prepareDigestAuth(); } // Set up our GET variables $this->get_args = $this->uri->uri_to_assoc();//获取参数 var_dump($this->get_args); // Set up out PUT variables var_dump(parse_str(file_get_contents('php://input'), $this->put_args)); parse_str(file_get_contents('php://input'), $this->put_args); // Merge both for one mega-args variable $this->args = array_merge($this->get_args, $this->put_args); // Which format should the data be returned in? $this->format = $this->_detect_format();//设置参数方式 json 、 xml } /* * Remap * * Requests are not made to methods directly The request will be for an "object". * this simply maps the object and method to the correct Controller method. */ function _remap($object_called) { $controller_method = $object_called.'_'.$this->method; if(method_exists($this, $controller_method)) { $this->$controller_method(); } else { show_404(); } } /* * Responce * * Takes pure data and optionally a status code, then creates the responce */ function responce($data = '', $http_code = 200) { $this->output->set_status_header($http_code); // If the method exists, call it if(method_exists($this, '_'.$this->format)) { // Set a XML header $this->output->set_header('Content-type: '.$this->supported_formats[$this->format]); $formatted_data = $this->{'_'.$this->format}($data); $this->output->set_output( $formatted_data ); } else { $this->output->set_output( $data ); } } /* * Detect format * * Detect which format should be used to output the data */ private function _detect_format() { if(array_key_exists('format', $this->args) && array_key_exists($this->args['format'], $this->supported_formats)) { return $this->args['format']; } // If a HTTP_ACCEPT header is present... if($this->input->server('HTTP_ACCEPT')) { // Check to see if it matches a supported format foreach(array_keys($this->supported_formats) as $format) { if(strpos($this->input->server('HTTP_ACCEPT'), $format) !== FALSE) { return $format; } } } // If it doesnt match any or no HTTP_ACCEPT header exists, uses the first (default) supported format list($default)=array_keys($this->supported_formats); return $default; } /* * Detect method * * Detect which method (POST, PUT, GET, DELETE) is being used */ private function _detect_method() { $method = strtolower($this->input->server('REQUEST_METHOD')); if(in_array($method, array('get', 'delete', 'post', 'put'))) { return $method; } return 'get'; } // INPUT FUNCTION -------------------------------------------------------------- public function get($key) { return array_key_exists($key, $this->get_args) ? $this->input->xss_clean( $this->get_args[$key] ) : $this->input->get($key) ; } public function post($key) { return $this->input->post($key); } public function put($key) { return array_key_exists($key, $this->put_args) ? $this->input->xss_clean( $this->put_args[$key] ) : FALSE ; } // SECURITY FUNCTIONS --------------------------------------------------------- private function _checkLogin($username = '', $password = NULL) { if(empty($username)) { return FALSE; } $valid_logins =& $this->config->item('rest_valid_logins'); if(!array_key_exists($username, $valid_logins)) { return FALSE; } // If actually NULL (not empty string) then do not check it if($password !== NULL) { if($valid_logins[$username] != $password) { return FALSE; } } return TRUE; } private function _prepareBasicAuth() { $username = NULL; $password = NULL; // mod_php if (isset($_SERVER['PHP_AUTH_USER'])) { $username = $_SERVER['PHP_AUTH_USER']; $password = $_SERVER['PHP_AUTH_PW']; } // most other servers elseif (isset($_SERVER['HTTP_AUTHENTICATION'])) { if (strpos(strtolower($_SERVER['HTTP_AUTHENTICATION']),'basic')===0) { list($username,$password) = explode(':',base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6))); } } if ( !$this->_checkLogin($username, $password) ) { $this->_forceLogin(); } } private function _prepareDigestAuth() { $uniqid = uniqid(""); // Empty argument for backward compatibility // We need to test which server authentication variable to use // because the PHP ISAPI module in IIS acts different from CGI if(isset($_SERVER['PHP_AUTH_DIGEST'])) { $digest_string = $_SERVER['PHP_AUTH_DIGEST']; } elseif(isset($_SERVER['HTTP_AUTHORIZATION'])) { $digest_string = $_SERVER['HTTP_AUTHORIZATION']; } else { $digest_string = ""; } /* The $_SESSION['error_prompted'] variabile is used to ask the password again if none given or if the user enters a wrong auth. informations. */ if ( empty($digest_string) ) { $this->_forceLogin($uniqid); exit; } // We need to retrieve authentication informations from the $auth_data variable preg_match_all('@(username|nonce|uri|nc|cnonce|qop|response)=[\'"]?([^\'",]+)@', $digest_string, $matches); $digest = array_combine($matches[1], $matches[2]); if ( !array_key_exists('username', $digest) || !$this->_checkLogin($digest['username']) ) { $this->responce(NULL, 401); exit; } $valid_logins =& $this->config->item('rest_valid_logins'); $valid_pass = $valid_logins[$digest['username']]; // This is the valid response expected $A1 = md5($digest['username'] . ':' . $this->config->item('rest_realm') . ':' . $valid_pass); $A2 = md5(strtoupper($this->method).':'.$digest['uri']); $valid_response = md5($A1.':'.$digest['nonce'].':'.$digest['nc'].':'.$digest['cnonce'].':'.$digest['qop'].':'.$A2); if ($digest['response'] != $valid_response) { $this->responce(NULL, 401); exit; } } private function _forceLogin($nonce = '') { header('HTTP/1.0 401 Unauthorized'); header('HTTP/1.1 401 Unauthorized'); if($this->config->item('rest_auth') == 'basic') { header('WWW-Authenticate: Basic realm="'.$this->config->item('rest_realm').'"'); } elseif($this->config->item('rest_auth') == 'digest') { header('WWW-Authenticate: Digest realm="'.$this->config->item('rest_realm'). '" qop="auth" nonce="'.$nonce.'" opaque="'.md5($this->config->item('rest_realm')).'"'); } echo 'Text to send if user hits Cancel button'; die(); } // FORMATING FUNCTIONS --------------------------------------------------------- // Format XML for output private function _xml($data = array(), $structure = NULL, $basenode = 'xml') { // turn off compatibility mode as simple xml throws a wobbly if you don't. if (ini_get('zend.ze1_compatibility_mode') == 1) { ini_set ('zend.ze1_compatibility_mode', 0); } if ($structure == NULL) { $structure = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$basenode />"); } // loop through the data passed in. foreach($data as $key => $value) { // no numeric keys in our xml please! if (is_numeric($key)) { // make string key... //$key = "item_". (string) $key; $key = "item"; } // replace anything not alpha numeric $key = preg_replace('/[^a-z0-9_-]/i', '', $key); // if there is another array found recrusively call this function if (is_array($value)) { $node = $structure->addChild($key); // recrusive call. $this->_xml($value, $node, $basenode); } else { // add single node. $value = htmlentities($value, ENT_NOQUOTES, "UTF-8"); $UsedKeys[] = $key; $structure->addChild($key, $value); } } // pass back as string. or simple xml object if you want! return $structure->asXML(); } // Format HTML for output private function _html($data = array()) { // Multi-dimentional array if(isset($data[0])) { $headings = array_keys($data[0]); } // Single array else { $headings = array_keys($data); } $this->load->library('table'); $this->table->set_heading($headings); foreach($data as &$row) { $this->table->add_row($row); } return $this->table->generate(); } // Format HTML for output private function _csv($data = array()) { // Multi-dimentional array if(isset($data[0])) { $headings = array_keys($data[0]); $output = implode(',', $headings)."\r\n"; foreach($data as &$row) { $output .= '"'.implode('","',$row)."\"\r\n"; } } // Single array else { $headings = array_keys($data); $output = implode(',', $headings)."\r\n"; $output .= '"'.implode('","',$data)."\"\r\n"; } return $output; } // Encode as JSON private function _json($data = array()) { return json_encode($data); } // Encode as Serialized array private function _serialize($data = array()) { return serialize($data); } // Encode raw PHP private function _php($data = array()) { return var_export($data); } } ?> ```
搭建好服务器之后,启动服务器
搭建好服务器之后,启动服务器,出现: DEBUG response status: 404 :/home/tclxa/.virtualenvs/zamboni/lib/python2.6/site-packages/pyelasticsearch/client.py:252 cilent.py文件如下: # -*- coding: utf-8 -*- from __future__ import absolute_import from datetime import datetime from operator import itemgetter from functools import wraps from logging import getLogger import re from six import (iterkeys, binary_type, text_type, string_types, integer_types, iteritems, PY3) from six.moves import xrange try: # PY3 from urllib.parse import urlencode, quote_plus except ImportError: # PY2 from urllib import urlencode, quote_plus import requests import simplejson as json # for use_decimal from simplejson import JSONDecodeError from pyelasticsearch.downtime import DowntimePronePool from pyelasticsearch.exceptions import (Timeout, ConnectionError, ElasticHttpError, InvalidJsonResponseError, ElasticHttpNotFoundError, IndexAlreadyExistsError) def _add_es_kwarg_docs(params, method): """ Add stub documentation for any args in ``params`` that aren't already in the docstring of ``method``. The stubs may not tell much about each arg, but they serve the important purpose of letting the user know that they're safe to use--we won't be paving over them in the future for something pyelasticsearch-specific. """ def docs_for_kwarg(p): return '\n :arg %s: See the ES docs.' % p doc = method.__doc__ if doc is not None: # It's none under python -OO. # Handle the case where there are no :arg declarations to key off: if '\n :arg' not in doc and params: first_param, params = params[0], params[1:] doc = doc.replace('\n (Insert es_kwargs here.)', docs_for_kwarg(first_param)) for p in params: if ('\n :arg %s: ' % p) not in doc: # Find the last documented arg so we can put our generated docs # after it. No need to explicitly compile this; the regex cache # should serve. insertion_point = re.search( r' :arg (.*?)(?=\n+ (?:$|[^: ]))', doc, re.MULTILINE | re.DOTALL).end() doc = ''.join([doc[:insertion_point], docs_for_kwarg(p), doc[insertion_point:]]) method.__doc__ = doc def es_kwargs(*args_to_convert): """ Mark which kwargs will become query string params in the eventual ES call. Return a decorator that grabs the kwargs of the given names, plus any beginning with "es_", subtracts them from the ordinary kwargs, and passes them to the decorated function through the ``query_params`` kwarg. The remaining kwargs and the args are passed through unscathed. Also, if any of the given kwargs are undocumented in the decorated method's docstring, add stub documentation for them. """ convertible_args = set(args_to_convert) def decorator(func): # Add docs for any missing query params: _add_es_kwarg_docs(args_to_convert, func) @wraps(func) def decorate(*args, **kwargs): # Make kwargs the map of normal kwargs and query_params the map of # kwargs destined for query string params: query_params = {} for k in list(iterkeys(kwargs)): # Make a copy; we mutate kwargs. if k.startswith('es_'): query_params[k[3:]] = kwargs.pop(k) elif k in convertible_args: query_params[k] = kwargs.pop(k) return func(*args, query_params=query_params, **kwargs) return decorate return decorator class ElasticSearch(object): """ An object which manages connections to elasticsearch and acts as a go-between for API calls to it This object is thread-safe. You can create one instance and share it among all threads. """ def __init__(self, urls, timeout=60, max_retries=0, revival_delay=300): """ :arg urls: A URL or iterable of URLs of ES nodes. These are full URLs with port numbers, like ``http://elasticsearch.example.com:9200``. :arg timeout: Number of seconds to wait for each request before raising Timeout :arg max_retries: How many other servers to try, in series, after a request times out or a connection fails :arg revival_delay: Number of seconds for which to avoid a server after it times out or is uncontactable """ if isinstance(urls, string_types): urls = [urls] urls = [u.rstrip('/') for u in urls] self.servers = DowntimePronePool(urls, revival_delay) self.revival_delay = revival_delay self.timeout = timeout self.max_retries = max_retries self.logger = getLogger('pyelasticsearch') self.session = requests.session() self.json_encoder = JsonEncoder def _concat(self, items): """ Return a comma-delimited concatenation of the elements of ``items``, with any occurrences of "_all" omitted. If ``items`` is a string, promote it to a 1-item list. """ # TODO: Why strip out _all? if items is None: return '' if isinstance(items, string_types): items = [items] return ','.join(i for i in items if i != '_all') def _to_query(self, obj): """ Convert a native-Python object to a unicode or bytestring representation suitable for a query string. """ # Quick and dirty thus far if isinstance(obj, string_types): return obj if isinstance(obj, bool): return 'true' if obj else 'false' if isinstance(obj, integer_types): return str(obj) if isinstance(obj, float): return repr(obj) # str loses precision. if isinstance(obj, (list, tuple)): return ','.join(self._to_query(o) for o in obj) iso = _iso_datetime(obj) if iso: return iso raise TypeError("_to_query() doesn't know how to represent %r in an ES" ' query string.' % obj) def _utf8(self, thing): """Convert any arbitrary ``thing`` to a utf-8 bytestring.""" if isinstance(thing, binary_type): return thing if not isinstance(thing, text_type): thing = text_type(thing) return thing.encode('utf-8') def _join_path(self, path_components): """ Smush together the path components, omitting '' and None ones. Unicodes get encoded to strings via utf-8. Incoming strings are assumed to be utf-8-encoded already. """ path = '/'.join(quote_plus(self._utf8(p), '') for p in path_components if p is not None and p != '') if not path.startswith('/'): path = '/' + path return path def send_request(self, method, path_components, body='', query_params=None, encode_body=True): """ Send an HTTP request to ES, and return the JSON-decoded response. This is mostly an internal method, but it also comes in handy if you need to use a brand new ES API that isn't yet explicitly supported by pyelasticsearch, while still taking advantage of our connection pooling and retrying. Retry the request on different servers if the first one is down and ``self.max_retries`` > 0. :arg method: An HTTP method, like "GET" :arg path_components: An iterable of path components, to be joined by "/" :arg body: The request body :arg query_params: A map of querystring param names to values or ``None`` :arg encode_body: Whether to encode the body of the request as JSON """ path = self._join_path(path_components) if query_params: path = '?'.join( [path, urlencode(dict((k, self._utf8(self._to_query(v))) for k, v in iteritems(query_params)))]) request_body = self._encode_json(body) if encode_body else body req_method = getattr(self.session, method.lower()) # We do our own retrying rather than using urllib3's; we want to retry # a different node in the cluster if possible, not the same one again # (which may be down). for attempt in xrange(self.max_retries + 1): server_url, was_dead = self.servers.get() url = server_url + path self.logger.debug( "Making a request equivalent to this: curl -X%s '%s' -d '%s'", method, url, request_body) try: resp = req_method( url, timeout=self.timeout, **({'data': request_body} if body else {})) except (ConnectionError, Timeout): self.servers.mark_dead(server_url) self.logger.info('%s marked as dead for %s seconds.', server_url, self.revival_delay) if attempt >= self.max_retries: raise else: if was_dead: self.servers.mark_live(server_url) break self.logger.debug('response status: %s', resp.status_code) print'****************************************************' print resp.status_code print'****************************************************' prepped_response = self._decode_response(resp) if resp.status_code >= 400: self._raise_exception(resp, prepped_response) self.logger.debug('got response %s', prepped_response) return prepped_response def _raise_exception(self, response, decoded_body): """Raise an exception based on an error-indicating response from ES.""" error_message = decoded_body.get('error', decoded_body) error_class = ElasticHttpError if response.status_code == 404: error_class = ElasticHttpNotFoundError elif (error_message.startswith('IndexAlreadyExistsException') or 'nested: IndexAlreadyExistsException' in error_message): error_class = IndexAlreadyExistsError raise error_class(response.status_code, error_message) def _encode_json(self, value): """ Convert a Python value to a form suitable for ElasticSearch's JSON DSL. """ return json.dumps(value, cls=self.json_encoder, use_decimal=True) def _decode_response(self, response): """Return a native-Python representation of a response's JSON blob.""" try: json_response = response.json() except JSONDecodeError: raise InvalidJsonResponseError(response) return json_response ## REST API @es_kwargs('routing', 'parent', 'timestamp', 'ttl', 'percolate', 'consistency', 'replication', 'refresh', 'timeout', 'fields') def index(self, index, doc_type, doc, id=None, overwrite_existing=True, query_params=None): """ Put a typed JSON document into a specific index to make it searchable. :arg index: The name of the index to which to add the document :arg doc_type: The type of the document :arg doc: A Python mapping object, convertible to JSON, representing the document :arg id: The ID to give the document. Leave blank to make one up. :arg overwrite_existing: Whether we should overwrite existing documents of the same ID and doctype :arg routing: A value hashed to determine which shard this indexing request is routed to :arg parent: The ID of a parent document, which leads this document to be routed to the same shard as the parent, unless ``routing`` overrides it. :arg timestamp: An explicit value for the (typically automatic) timestamp associated with a document, for use with ``ttl`` and such :arg ttl: The time until this document is automatically removed from the index. Can be an integral number of milliseconds or a duration like '1d'. :arg percolate: An indication of which percolator queries, registered against this index, should be checked against the new document: '*' or a query string like 'color:green' :arg consistency: An indication of how many active shards the contact node should demand to see in order to let the index operation succeed: 'one', 'quorum', or 'all' :arg replication: Set to 'async' to return from ES before finishing replication. :arg refresh: Pass True to refresh the index after adding the document. :arg timeout: A duration to wait for the relevant primary shard to become available, in the event that it isn't: for example, "5m" See `ES's index API`_ for more detail. .. _`ES's index API`: http://www.elasticsearch.org/guide/reference/api/index_.html """ # :arg query_params: A map of other querystring params to pass along to # ES. This lets you use future ES features without waiting for an # update to pyelasticsearch. If we just used **kwargs for this, ES # could start using a querystring param that we already used as a # kwarg, and we'd shadow it. Name these params according to the names # they have in ES's REST API, but prepend "\es_": for example, # ``es_version=2``. # TODO: Support version along with associated "preference" and # "version_type" params. if not overwrite_existing: query_params['op_type'] = 'create' return self.send_request('POST' if id is None else 'PUT', [index, doc_type, id], doc, query_params) @es_kwargs('consistency', 'refresh') def bulk_index(self, index, doc_type, docs, id_field='id', parent_field='_parent', query_params=None): """ Index a list of documents as efficiently as possible. :arg index: The name of the index to which to add the document :arg doc_type: The type of the document :arg docs: An iterable of Python mapping objects, convertible to JSON, representing documents to index :arg id_field: The field of each document that holds its ID :arg parent_field: The field of each document that holds its parent ID, if any. Removed from document before indexing. See `ES's bulk API`_ for more detail. .. _`ES's bulk API`: http://www.elasticsearch.org/guide/reference/api/bulk.html """ body_bits = [] if not docs: raise ValueError('No documents provided for bulk indexing!') for doc in docs: action = {'index': {'_index': index, '_type': doc_type}} if doc.get(id_field) is not None: action['index']['_id'] = doc[id_field] if doc.get(parent_field) is not None: action['index']['_parent'] = doc.pop(parent_field) body_bits.append(self._encode_json(action)) body_bits.append(self._encode_json(doc)) # Need the trailing newline. body = '\n'.join(body_bits) + '\n' return self.send_request('POST', ['_bulk'], body, encode_body=False, query_params=query_params) @es_kwargs('routing', 'parent', 'replication', 'consistency', 'refresh') def delete(self, index, doc_type, id, query_params=None): """ Delete a typed JSON document from a specific index based on its ID. :arg index: The name of the index from which to delete :arg doc_type: The type of the document to delete :arg id: The (string or int) ID of the document to delete See `ES's delete API`_ for more detail. .. _`ES's delete API`: http://www.elasticsearch.org/guide/reference/api/delete.html """ # id should never be None, and it's not particular dangerous # (equivalent to deleting a doc with ID "None", but it's almost # certainly not what the caller meant: if id is None or id == '': raise ValueError('No ID specified. To delete all documents in ' 'an index, use delete_all().') return self.send_request('DELETE', [index, doc_type, id], query_params=query_params) @es_kwargs('routing', 'parent', 'replication', 'consistency', 'refresh') def delete_all(self, index, doc_type, query_params=None): """ Delete all documents of the given doctype from an index. :arg index: The name of the index from which to delete. ES does not support this being empty or "_all" or a comma-delimited list of index names (in 0.19.9). :arg doc_type: The name of a document type See `ES's delete API`_ for more detail. .. _`ES's delete API`: http://www.elasticsearch.org/guide/reference/api/delete.html """ return self.send_request('DELETE', [index, doc_type], query_params=query_params) @es_kwargs('q', 'df', 'analyzer', 'default_operator', 'source' 'routing', 'replication', 'consistency') def delete_by_query(self, index, doc_type, query, query_params=None): """ Delete typed JSON documents from a specific index based on query. :arg index: An index or iterable thereof from which to delete :arg doc_type: The type of document or iterable thereof to delete :arg query: A dictionary that will convert to ES's query DSL or a string that will serve as a textual query to be passed as the ``q`` query string parameter. (Passing the ``q`` kwarg yourself is deprecated.) See `ES's delete-by-query API`_ for more detail. .. _`ES's delete-by-query API`: http://www.elasticsearch.org/guide/reference/api/delete-by-query.html """ if isinstance(query, string_types) and 'q' not in query_params: query_params['q'] = query body = '' else: body = query return self.send_request( 'DELETE', [self._concat(index), self._concat(doc_type), '_query'], body, query_params=query_params) @es_kwargs('realtime', 'fields', 'routing', 'preference', 'refresh') def get(self, index, doc_type, id, query_params=None): """ Get a typed JSON document from an index by ID. :arg index: The name of the index from which to retrieve :arg doc_type: The type of document to get :arg id: The ID of the document to retrieve See `ES's get API`_ for more detail. .. _`ES's get API`: http://www.elasticsearch.org/guide/reference/api/get.html """ return self.send_request('GET', [index, doc_type, id], query_params=query_params) @es_kwargs() def multi_get(self, ids, index=None, doc_type=None, fields=None, query_params=None): """ Get multiple typed JSON documents from ES. :arg ids: An iterable, each element of which can be either an a dict or an id (int or string). IDs are taken to be document IDs. Dicts are passed through the Multi Get API essentially verbatim, except that any missing ``_type``, ``_index``, or ``fields`` keys are filled in from the defaults given in the ``index``, ``doc_type``, and ``fields`` args. :arg index: Default index name from which to retrieve :arg doc_type: Default type of document to get :arg fields: Default fields to return See `ES's Multi Get API`_ for more detail. .. _`ES's Multi Get API`: http://www.elasticsearch.org/guide/reference/api/multi-get.html """ doc_template = dict( filter( itemgetter(1), [('_index', index), ('_type', doc_type), ('fields', fields)])) docs = [] for id in ids: doc = doc_template.copy() if isinstance(id, dict): doc.update(id) else: doc['_id'] = id docs.append(doc) return self.send_request( 'GET', ['_mget'], {'docs': docs}, query_params=query_params) @es_kwargs('routing', 'parent', 'timeout', 'replication', 'consistency', 'percolate', 'refresh', 'retry_on_conflict', 'fields') def update(self, index, doc_type, id, script=None, params=None, lang=None, query_params=None, doc=None, upsert=None): """ Update an existing document. Raise ``TypeError`` if ``script``, ``doc`` and ``upsert`` are all unspecified. :arg index: The name of the index containing the document :arg doc_type: The type of the document :arg id: The ID of the document :arg script: The script to be used to update the document :arg params: A dict of the params to be put in scope of the script :arg lang: The language of the script. Omit to use the default, specified by ``script.default_lang``. :arg doc: A partial document to be merged into the existing document :arg upsert: The content for the new document created if the document does not exist """ if script is None and doc is None and upsert is None: raise TypeError('At least one of the script, doc, or upsert ' 'kwargs must be provided.') body = {} if script: body['script'] = script if lang and script: body['lang'] = lang if doc: body['doc'] = doc if upsert: body['upsert'] = upsert if params: body['params'] = params return self.send_request( 'POST', [index, doc_type, id, '_update'], body=body, query_params=query_params) def _search_or_count(self, kind, query, index=None, doc_type=None, query_params=None): if isinstance(query, string_types): query_params['q'] = query body = '' else: body = query return self.send_request( 'GET', [self._concat(index), self._concat(doc_type), kind], body, query_params=query_params) @es_kwargs('routing', 'size') def search(self, query, **kwargs): """ Execute a search query against one or more indices and get back search hits. :arg query: A dictionary that will convert to ES's query DSL or a string that will serve as a textual query to be passed as the ``q`` query string parameter :arg index: An index or iterable of indexes to search. Omit to search all. :arg doc_type: A document type or iterable thereof to search. Omit to search all. :arg size: Limit the number of results to ``size``. Use with ``es_from`` to implement paginated searching. See `ES's search API`_ for more detail. .. _`ES's search API`: http://www.elasticsearch.org/guide/reference/api/search/ """ return self._search_or_count('_search', query, **kwargs) @es_kwargs('df', 'analyzer', 'default_operator', 'source', 'routing') def count(self, query, **kwargs): """ Execute a query against one or more indices and get hit count. :arg query: A dictionary that will convert to ES's query DSL or a string that will serve as a textual query to be passed as the ``q`` query string parameter :arg index: An index or iterable of indexes to search. Omit to search all. :arg doc_type: A document type or iterable thereof to search. Omit to search all. See `ES's count API`_ for more detail. .. _`ES's count API`: http://www.elasticsearch.org/guide/reference/api/count.html """ return self._search_or_count('_count', query, **kwargs) @es_kwargs() def get_mapping(self, index=None, doc_type=None, query_params=None): """ Fetch the mapping definition for a specific index and type. :arg index: An index or iterable thereof :arg doc_type: A document type or iterable thereof Omit both arguments to get mappings for all types and indexes. See `ES's get-mapping API`_ for more detail. .. _`ES's get-mapping API`: http://www.elasticsearch.org/guide/reference/api/admin-indices-get-mapping.html """ # TODO: Think about turning index=None into _all if doc_type is non- # None, per the ES doc page. return self.send_request( 'GET', [self._concat(index), self._concat(doc_type), '_mapping'], query_params=query_params) @es_kwargs('ignore_conflicts') def put_mapping(self, index, doc_type, mapping, query_params=None): """ Register specific mapping definition for a specific type against one or more indices. :arg index: An index or iterable thereof :arg doc_type: The document type to set the mapping of :arg mapping: A dict representing the mapping to install. For example, this dict can have top-level keys that are the names of doc types. See `ES's put-mapping API`_ for more detail. .. _`ES's put-mapping API`: http://www.elasticsearch.org/guide/reference/api/admin-indices-put-mapping.html """ # TODO: Perhaps add a put_all_mappings() for consistency and so we # don't need to expose the "_all" magic string. We haven't done it yet # since this routine is not dangerous: ES makes you explicily pass # "_all" to update all mappings. return self.send_request( 'PUT', [self._concat(index), doc_type, '_mapping'], mapping, query_params=query_params) @es_kwargs('search_type', 'search_indices', 'search_types', 'search_scroll', 'search_size', 'search_from', 'like_text', 'percent_terms_to_match', 'min_term_freq', 'max_query_terms', 'stop_words', 'min_doc_freq', 'max_doc_freq', 'min_word_len', 'max_word_len', 'boost_terms', 'boost', 'analyzer') def more_like_this(self, index, doc_type, id, mlt_fields, body='', query_params=None): """ Execute a "more like this" search query against one or more fields and get back search hits. :arg index: The index to search and where the document for comparison lives :arg doc_type: The type of document to find others like :arg id: The ID of the document to find others like :arg mlt_fields: The list of fields to compare on :arg body: A dictionary that will convert to ES's query DSL and be passed as the request body See `ES's more-like-this API`_ for more detail. .. _`ES's more-like-this API`: http://www.elasticsearch.org/guide/reference/api/more-like-this.html """ query_params['mlt_fields'] = self._concat(mlt_fields) return self.send_request('GET', [index, doc_type, id, '_mlt'], body=body, query_params=query_params) ## Index Admin API @es_kwargs('recovery', 'snapshot') def status(self, index=None, query_params=None): """ Retrieve the status of one or more indices :arg index: An index or iterable thereof See `ES's index-status API`_ for more detail. .. _`ES's index-status API`: http://www.elasticsearch.org/guide/reference/api/admin-indices-status.html """ return self.send_request('GET', [self._concat(index), '_status'], query_params=query_params) @es_kwargs() def update_aliases(self, settings, query_params=None): """ Add, remove, or update aliases in bulk. :arg settings: a dictionary specifying the actions to perform See `ES's admin-indices-aliases API`_. .. _`ES's admin-indices-aliases API`: http://www.elasticsearch.org/guide/reference/api/admin-indices-aliases.html """ return self.send_request('POST', ['_aliases'], body=settings, query_params=query_params) @es_kwargs() def aliases(self, index=None, query_params=None): """ Retrieve a listing of aliases :arg index: the name of an index or an iterable of indices See `ES's admin-indices-aliases API`_. .. _`ES's admin-indices-aliases API`: http://www.elasticsearch.org/guide/reference/api/admin-indices-aliases.html """ return self.send_request('GET', [self._concat(index), '_aliases'], query_params=query_params) @es_kwargs() def create_index(self, index, settings=None, query_params=None): """ Create an index with optional settings. :arg index: The name of the index to create :arg settings: A dictionary of settings If the index already exists, raise :class:`~pyelasticsearch.exceptions.IndexAlreadyExistsError`. See `ES's create-index API`_ for more detail. .. _`ES's create-index API`: http://www.elasticsearch.org/guide/reference/api/admin-indices-create-index.html """ return self.send_request('PUT', [index], body=settings, query_params=query_params) @es_kwargs() def delete_index(self, index, query_params=None): """ Delete an index. :arg index: An index or iterable thereof to delete If the index is not found, raise :class:`~pyelasticsearch.exceptions.ElasticHttpNotFoundError`. See `ES's delete-index API`_ for more detail. .. _`ES's delete-index API`: http://www.elasticsearch.org/guide/reference/api/admin-indices-delete-index.html """ if not index: raise ValueError('No indexes specified. To delete all indexes, use' ' delete_all_indexes().') return self.send_request('DELETE', [self._concat(index)], query_params=query_params) def delete_all_indexes(self, **kwargs): """Delete all indexes.""" return self.delete_index('_all', **kwargs) @es_kwargs() def close_index(self, index, query_params=None): """ Close an index. :arg index: The index to close See `ES's close-index API`_ for more detail. .. _`ES's close-index API`: http://www.elasticsearch.org/guide/reference/api/admin-indices-open-close.html """ return self.send_request('POST', [index, '_close'], query_params=query_params) @es_kwargs() def open_index(self, index, query_params=None): """ Open an index. :arg index: The index to open See `ES's open-index API`_ for more detail. .. _`ES's open-index API`: http://www.elasticsearch.org/guide/reference/api/admin-indices-open-close.html """ return self.send_request('POST', [index, '_open'], query_params=query_params) @es_kwargs() def get_settings(self, index, query_params=None): """ Get the settings of one or more indexes. :arg index: An index or iterable of indexes See `ES's get-settings API`_ for more detail. .. _`ES's get-settings API`: http://www.elasticsearch.org/guide/reference/api/admin-indices-get-settings.html """ return self.send_request('GET', [self._concat(index), '_settings'], query_params=query_params) @es_kwargs() def update_settings(self, index, settings, query_params=None): """ Change the settings of one or more indexes. :arg index: An index or iterable of indexes :arg settings: A dictionary of settings See `ES's update-settings API`_ for more detail. .. _`ES's update-settings API`: http://www.elasticsearch.org/guide/reference/api/admin-indices-update-settings.html """ if not index: raise ValueError('No indexes specified. To update all indexes, use' ' update_all_settings().') # If we implement the "update cluster settings" API, call that # update_cluster_settings(). return self.send_request('PUT', [self._concat(index), '_settings'], body=settings, query_params=query_params) @es_kwargs() def update_all_settings(self, settings, query_params=None): """ Update the settings of all indexes. :arg settings: A dictionary of settings See `ES's update-settings API`_ for more detail. .. _`ES's update-settings API`: http://www.elasticsearch.org/guide/reference/api/admin-indices-update-settings.html """ return self.send_request('PUT', ['_settings'], body=settings, query_params=query_params) @es_kwargs('refresh') def flush(self, index=None, query_params=None): """ Flush one or more indices (clear memory). :arg index: An index or iterable of indexes See `ES's flush API`_ for more detail. .. _`ES's flush API`: http://www.elasticsearch.org/guide/reference/api/admin-indices-flush.html """ return self.send_request('POST', [self._concat(index), '_flush'], query_params=query_params) @es_kwargs() def refresh(self, index=None, query_params=None): """ Refresh one or more indices. :arg index: An index or iterable of indexes See `ES's refresh API`_ for more detail. .. _`ES's refresh API`: http://www.elasticsearch.org/guide/reference/api/admin-indices-refresh.html """ return self.send_request('POST', [self._concat(index), '_refresh'], query_params=query_params) @es_kwargs() def gateway_snapshot(self, index=None, query_params=None): """ Gateway snapshot one or more indices. :arg index: An index or iterable of indexes See `ES's gateway-snapshot API`_ for more detail. .. _`ES's gateway-snapshot API`: http://www.elasticsearch.org/guide/reference/api/admin-indices-gateway-snapshot.html """ return self.send_request( 'POST', [self._concat(index), '_gateway', 'snapshot'], query_params=query_params) @es_kwargs('max_num_segments', 'only_expunge_deletes', 'refresh', 'flush', 'wait_for_merge') def optimize(self, index=None, query_params=None): """ Optimize one or more indices. :arg index: An index or iterable of indexes See `ES's optimize API`_ for more detail. .. _`ES's optimize API`: http://www.elasticsearch.org/guide/reference/api/admin-indices-optimize.html """ return self.send_request('POST', [self._concat(index), '_optimize'], query_params=query_params) @es_kwargs('level', 'wait_for_status', 'wait_for_relocating_shards', 'wait_for_nodes', 'timeout') def health(self, index=None, query_params=None): """ Report on the health of the cluster or certain indices. :arg index: The index or iterable of indexes to examine See `ES's cluster-health API`_ for more detail. .. _`ES's cluster-health API`: http://www.elasticsearch.org/guide/reference/api/admin-cluster-health.html """ return self.send_request( 'GET', ['_cluster', 'health', self._concat(index)], query_params=query_params) @es_kwargs('filter_nodes', 'filter_routing_table', 'filter_metadata', 'filter_blocks', 'filter_indices') def cluster_state(self, query_params=None): """ The cluster state API allows to get comprehensive state information of the whole cluster. (Insert es_kwargs here.) See `ES's cluster-state API`_ for more detail. .. _`ES's cluster-state API`: http://www.elasticsearch.org/guide/reference/api/admin-cluster-state.html """ return self.send_request( 'GET', ['_cluster', 'state'], query_params=query_params) @es_kwargs() def percolate(self, index, doc_type, doc, query_params=None): """ Run a JSON document through the registered percolator queries, and return which ones match. :arg index: The name of the index to which the document pretends to belong :arg doc_type: The type the document should be treated as if it has :arg doc: A Python mapping object, convertible to JSON, representing the document Use :meth:`index()` to register percolators. See `ES's percolate API`_ for more detail. .. _`ES's percolate API`: http://www.elasticsearch.org/guide/reference/api/percolate/ """ return self.send_request('GET', [index, doc_type, '_percolate'], doc, query_params=query_params) class JsonEncoder(json.JSONEncoder): def default(self, value): """Convert more Python data types to ES-understandable JSON.""" iso = _iso_datetime(value) if iso: return iso if not PY3 and isinstance(value, str): return unicode(value, errors='replace') # TODO: Be stricter. if isinstance(value, set): return list(value) return super(JsonEncoder, self).default(value) def _iso_datetime(value): """ If value appears to be something datetime-like, return it in ISO format. Otherwise, return None. """ if hasattr(value, 'strftime'): if hasattr(value, 'hour'): return value.isoformat() else: return '%sT00:00:00' % value.isoformat()
终于明白阿里百度这样的大公司,为什么面试经常拿ThreadLocal考验求职者了
点击上面↑「爱开发」关注我们每晚10点,捕获技术思考和创业资源洞察什么是ThreadLocalThreadLocal是一个本地线程副本变量工具类,各个线程都拥有一份线程私...
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
Linux(服务器编程):15---两种高效的事件处理模式(reactor模式、proactor模式)
前言 同步I/O模型通常用于实现Reactor模式 异步I/O模型则用于实现Proactor模式 最后我们会使用同步I/O方式模拟出Proactor模式 一、Reactor模式 Reactor模式特点 它要求主线程(I/O处理单元)只负责监听文件描述符上是否有事件发生,有的话就立即将时间通知工作线程(逻辑单元)。除此之外,主线程不做任何其他实质性的工作 读写数据,接受新的连接,以及处...
阿里面试官问我:如何设计秒杀系统?我的回答让他比起大拇指
你知道的越多,你不知道的越多 点赞再看,养成习惯 GitHub上已经开源 https://github.com/JavaFamily 有一线大厂面试点脑图和个人联系方式,欢迎Star和指教 前言 Redis在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在Redis的使用和原理方面对小伙伴们进行360°的刁难。 作为一个在互联网公司面一次拿一次Offer的面霸,打败了...
五年程序员记流水账式的自白。
不知觉已中码龄已突破五年,一路走来从起初铁憨憨到现在的十九线程序员,一路成长,虽然不能成为高工,但是也能挡下一面,从15年很火的android开始入坑,走过java、.Net、QT,目前仍处于android和.net交替开发中。 毕业到现在一共就职过两家公司,目前是第二家,公司算是半个创业公司,所以基本上都会身兼多职。比如不光要写代码,还要写软著、软著评测、线上线下客户对接需求收集...
C语言魔塔游戏
很早就很想写这个,今天终于写完了。 游戏截图: 编译环境: VS2017 游戏需要一些图片,如果有想要的或者对游戏有什么看法的可以加我的QQ 2985486630 讨论,如果暂时没有回应,可以在博客下方留言,到时候我会看到。 下面我来介绍一下游戏的主要功能和实现方式 首先是玩家的定义,使用结构体,这个名字是可以自己改变的 struct gamerole { char n...
一文详尽系列之模型评估指标
点击上方“Datawhale”,选择“星标”公众号第一时间获取价值内容在机器学习领域通常会根据实际的业务场景拟定相应的不同的业务指标,针对不同机器学习问题如回归、分类、排...
究竟你适不适合买Mac?
我清晰的记得,刚买的macbook pro回到家,开机后第一件事情,就是上了淘宝网,花了500元钱,找了一个上门维修电脑的师傅,上门给我装了一个windows系统。。。。。。 表砍我。。。 当时买mac的初衷,只是想要个固态硬盘的笔记本,用来运行一些复杂的扑克软件。而看了当时所有的SSD笔记本后,最终决定,还是买个好(xiong)看(da)的。 已经有好几个朋友问我mba怎么样了,所以今天尽量客观...
程序员一般通过什么途径接私活?
二哥,你好,我想知道一般程序猿都如何接私活,我也想接,能告诉我一些方法吗? 上面是一个读者“烦不烦”问我的一个问题。其实不止是“烦不烦”,还有很多读者问过我类似这样的问题。 我接的私活不算多,挣到的钱也没有多少,加起来不到 20W。说实话,这个数目说出来我是有点心虚的,毕竟太少了,大家轻喷。但我想,恰好配得上“一般程序员”这个称号啊。毕竟苍蝇再小也是肉,我也算是有经验的人了。 唾弃接私活、做外...
压测学习总结(1)——高并发性能指标:QPS、TPS、RT、吞吐量详解
一、QPS,每秒查询 QPS:Queries Per Second意思是“每秒查询率”,是一台服务器每秒能够相应的查询次数,是对一个特定的查询服务器在规定时间内所处理流量多少的衡量标准。互联网中,作为域名系统服务器的机器的性能经常用每秒查询率来衡量。 二、TPS,每秒事务 TPS:是TransactionsPerSecond的缩写,也就是事务数/秒。它是软件测试结果的测量单位。一个事务是指一...
Python爬虫爬取淘宝,京东商品信息
小编是一个理科生,不善长说一些废话。简单介绍下原理然后直接上代码。 使用的工具(Python+pycharm2019.3+selenium+xpath+chromedriver)其中要使用pycharm也可以私聊我selenium是一个框架可以通过pip下载 pip installselenium -ihttps://pypi.tuna.tsinghua.edu.cn/simple/ ...
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
Java工作4年来应聘要16K最后没要,细节如下。。。
前奏: 今天2B哥和大家分享一位前几天面试的一位应聘者,工作4年26岁,统招本科。 以下就是他的简历和面试情况。 基本情况: 专业技能: 1、&nbsp;熟悉Sping了解SpringMVC、SpringBoot、Mybatis等框架、了解SpringCloud微服务 2、&nbsp;熟悉常用项目管理工具:SVN、GIT、MAVEN、Jenkins 3、&nbsp;熟悉Nginx、tomca...
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆每天早上8:30推送 作者|Mr.K 编辑| Emma 来源|技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯...
程序员该看的几部电影
1、骇客帝国(1999) 概念:在线/离线,递归,循环,矩阵等 剧情简介: 不久的将来,网络黑客尼奥对这个看似正常的现实世界产生了怀疑。 他结识了黑客崔妮蒂,并见到了黑客组织的首领墨菲斯。 墨菲斯告诉他,现实世界其实是由一个名叫“母体”的计算机人工智能系统控制,人们就像他们饲养的动物,没有自由和思想,而尼奥就是能够拯救人类的救世主。 可是,救赎之路从来都不会一帆风顺,到底哪里才是真实的世界?如何...
Python绘图,圣诞树,花,爱心 | Turtle篇
每周每日,分享Python实战代码,入门资料,进阶资料,基础语法,爬虫,数据分析,web网站,机器学习,深度学习等等。 公众号回复【进群】沟通交流吧,QQ扫码进群学习吧 微信群 QQ群 1.画圣诞树 import turtle screen = turtle.Screen() screen.setup(800,600) circle = turtle.Turtle()...
作为一个程序员,CPU的这些硬核知识你必须会!
CPU对每个程序员来说,是个既熟悉又陌生的东西? 如果你只知道CPU是中央处理器的话,那可能对你并没有什么用,那么作为程序员的我们,必须要搞懂的就是CPU这家伙是如何运行的,尤其要搞懂它里面的寄存器是怎么一回事,因为这将让你从底层明白程序的运行机制。 随我一起,来好好认识下CPU这货吧 把CPU掰开来看 对于CPU来说,我们首先就要搞明白它是怎么回事,也就是它的内部构造,当然,CPU那么牛的一个东...
还记得那个提速8倍的IDEA插件吗?VS Code版本也发布啦!!
去年,阿里云发布了本地 IDE 插件 Cloud Toolkit,仅 IntelliJ IDEA 一个平台,就有 15 万以上的开发者进行了下载,体验了一键部署带来的开发便利。时隔一年的今天,阿里云正式发布了 Visual Studio Code 版本,全面覆盖前端开发者,帮助前端实现一键打包部署,让开发提速 8 倍。 VSCode 版本的插件,目前能做到什么? 安装插件之后,开发者可以立即体验...
破14亿,Python分析我国存在哪些人口危机!
一、背景 二、爬取数据 三、数据分析 1、总人口 2、男女人口比例 3、人口城镇化 4、人口增长率 5、人口老化(抚养比) 6、各省人口 7、世界人口 四、遇到的问题 遇到的问题 1、数据分页,需要获取从1949-2018年数据,观察到有近20年参数:LAST20,由此推测获取近70年的参数可设置为:LAST70 2、2019年数据没有放上去,可以手动添加上去 3、将数据进行 行列转换 4、列名...
2019年除夕夜的有感而发
天气:小雨(加小雪) 温度:3摄氏度 空气:严重污染(399) 风向:北风 风力:微风 现在是除夕夜晚上十点钟,再有两个小时就要新的一年了; 首先要说的是我没患病,至少现在是没有患病;但是心情确像患了病一样沉重; 现在这个时刻应该大部分家庭都在看春晚吧,或许一家人团团圆圆的坐在一起,或许因为某些特殊原因而不能团圆;但不管是身在何处,身处什么境地,我都想对每一个人说一句:新年快乐! 不知道csdn这...
听说想当黑客的都玩过这个Monyer游戏(1~14攻略)
第零关 进入传送门开始第0关(游戏链接) 请点击链接进入第1关: 连接在左边→ ←连接在右边 看不到啊。。。。(只能看到一堆大佬做完的留名,也能看到菜鸡的我,在后面~~) 直接fn+f12吧 &lt;span&gt;连接在左边→&lt;/span&gt; &lt;a href="first.php"&gt;&lt;/a&gt; &lt;span&gt;←连接在右边&lt;/span&gt; o...
在家远程办公效率低?那你一定要收好这个「在家办公」神器!
相信大家都已经收到国务院延长春节假期的消息,接下来,在家远程办公可能将会持续一段时间。 但是问题来了。远程办公不是人在电脑前就当坐班了,相反,对于沟通效率,文件协作,以及信息安全都有着极高的要求。有着非常多的挑战,比如: 1在异地互相不见面的会议上,如何提高沟通效率? 2文件之间的来往反馈如何做到及时性?如何保证信息安全? 3如何规划安排每天工作,以及如何进行成果验收? ...... ...
作为一个程序员,内存和磁盘的这些事情,你不得不知道啊!!!
截止目前,我已经分享了如下几篇文章: 一个程序在计算机中是如何运行的?超级干货!!! 作为一个程序员,CPU的这些硬核知识你必须会! 作为一个程序员,内存的这些硬核知识你必须懂! 这些知识可以说是我们之前都不太重视的基础知识,可能大家在上大学的时候都学习过了,但是嘞,当时由于老师讲解的没那么有趣,又加上这些知识本身就比较枯燥,所以嘞,大家当初几乎等于没学。 再说啦,学习这些,也看不出来有什么用啊!...
2020年的1月,我辞掉了我的第一份工作
其实,这篇文章,我应该早点写的,毕竟现在已经2月份了。不过一些其它原因,或者是我的惰性、还有一些迷茫的念头,让自己迟迟没有试着写一点东西,记录下,或者说是总结下自己前3年的工作上的经历、学习的过程。 我自己知道的,在写自己的博客方面,我的文笔很一般,非技术类的文章不想去写;另外我又是一个还比较热衷于技术的人,而平常复杂一点的东西,如果想写文章写的清楚点,是需要足够...
别低估自己的直觉,也别高估自己的智商
所有群全部吵翻天,朋友圈全部沦陷,公众号疯狂转发。这两周没怎么发原创,只发新闻,可能有人注意到了。我不是懒,是文章写了却没发,因为大家的关注力始终在这次的疫情上面,发了也没人看。当然,我...
这个世界上人真的分三六九等,你信吗?
偶然间,在知乎上看到一个问题 一时间,勾起了我深深的回忆。 以前在厂里打过两次工,做过家教,干过辅导班,做过中介。零下几度的晚上,贴过广告,满脸、满手地长冻疮。 再回首那段岁月,虽然苦,但让我学会了坚持和忍耐。让我明白了,在这个世界上,无论环境多么的恶劣,只要心存希望,星星之火,亦可燎原。 下文是原回答,希望能对你能有所启发。 如果我说,这个世界上人真的分三六九等,...
节后首个工作日,企业们集体开晨会让钉钉挂了
By 超神经场景描述:昨天 2 月 3 日,是大部分城市号召远程工作的第一天,全国有接近 2 亿人在家开始远程办公,钉钉上也有超过 1000 万家企业活跃起来。关键词:十一出行 人脸...
Java基础知识点梳理
虽然已经在实际工作中经常与java打交道,但是一直没系统地对java这门语言进行梳理和总结,掌握的知识也比较零散。恰好利用这段时间重新认识下java,并对一些常见的语法和知识点做个总结与回顾,一方面为了加深印象,方便后面查阅,一方面为了掌握好Android打下基础。
2020年全新Java学习路线图,含配套视频,学完即为中级Java程序员!!
新的一年来临,突如其来的疫情打破了平静的生活! 在家的你是否很无聊,如果无聊就来学习吧! 世上只有一种投资只赚不赔,那就是学习!!! 传智播客于2020年升级了Java学习线路图,硬核升级,免费放送! 学完你就是中级程序员,能更快一步找到工作! 一、Java基础 JavaSE基础是Java中级程序员的起点,是帮助你从小白到懂得编程的必经之路。 在Java基础板块中有6个子模块的学...
B 站上有哪些很好的学习资源?
哇说起B站,在小九眼里就是宝藏般的存在,放年假宅在家时一天刷6、7个小时不在话下,更别提今年的跨年晚会,我简直是跪着看完的!! 最早大家聚在在B站是为了追番,再后来我在上面刷欧美新歌和漂亮小姐姐的舞蹈视频,最近两年我和周围的朋友们已经把B站当作学习教室了,而且学习成本还免费,真是个励志的好平台ヽ(.◕ฺˇд ˇ◕ฺ;)ノ 下面我们就来盘点一下B站上优质的学习资源: 综合类 Oeasy: 综合...
如何优雅地打印一个Java对象?
你好呀,我是沉默王二,一个和黄家驹一样身高,和刘德华一样颜值的程序员。虽然已经写了十多年的 Java 代码,但仍然觉得自己是个菜鸟(请允许我惭愧一下)。 在一个月黑风高的夜晚,我思前想后,觉得再也不能这么蹉跎下去了。于是痛下决心,准备通过输出的方式倒逼输入,以此来修炼自己的内功,从而进阶成为一名真正意义上的大神。与此同时,希望这些文章能够帮助到更多的读者,让大家在学习的路上不再寂寞、空虚和冷。 ...
相关热词 c# 压缩图片好麻烦 c#计算数组中的平均值 c#获取路由参数 c#日期精确到分钟 c#自定义异常必须继承 c#查表并返回值 c# 动态 表达式树 c# 监控方法耗时 c# listbox c#chart显示滚动条
立即提问