IT专家为什么返回生成的HTML而不是JSON是不好的做法或者是吗.docx
《IT专家为什么返回生成的HTML而不是JSON是不好的做法或者是吗.docx》由会员分享,可在线阅读,更多相关《IT专家为什么返回生成的HTML而不是JSON是不好的做法或者是吗.docx(10页珍藏版)》请在冰豆网上搜索。
IT专家为什么返回生成的HTML而不是JSON是不好的做法或者是吗
本文由我司收集整编,推荐下载,如有疑问,请与我司联系
为什么返回生成的HTML而不是JSON是不好的做法?
或者是吗?
ItisquiteeasytoloadHTMLcontentfromyourcustomURLs/Webservicesusing
JQueryoranyothersimilarframework.I’veusedthisapproachmanytimesandtillnow
andfoundtheperformancesatisfactory.
使用JQuery或其他类似框架从自定义url/Web服务加载HTML内容非常容易。
我已经多次使用这种方法,到目前为止,我发现性能令人满意。
Butallthebooks,alltheexpertsaretryingtogetmetouseJSONinsteadofgenerated
HTML.How’sitmuchmoresuperiorthanHTML?
但是所有的书籍,所有的专家都试图让我使用JSON而不是生成的HTML。
它比
HTML有什么优势呢?
Isitverymuchfaster?
Doesithaveaverymuchlesserloadontheserver?
快得多吗?
它在服务器上的负载要小得多吗?
OntheothersideIhavesomereasonsforusinggeneratedHTML.
另一方面,我有一些使用生成的HTML的理由。
It’ssimplemarkup,andoftenjustascompactoractuallymorecompactthanJSON.
它是简单的标记,通常和JSON一样紧凑或者更紧凑。
It’slesserrorpronecauseall
you’regettingismarkup,andnocode.它不容易出错,因为您得到的只是标记,没有
代码。
Itwillbefastertoprograminmostcasescauseyouwon’thavetowritecode
separatelyfortheclientend.在大多数情况下,编程会更快,因为您不必为客户端单
独编写代码。
Whichsideareyouonandwhy?
你站在哪一边,为什么?
235
I’mabitonbothsides,actually:
事实上,我有点两面性:
WhenwhatIneedonthejavascriptsideisdata,IuseJSON当我在javascript端需
要的是数据时,我使用JSONWhenwhatIneedonthejavascriptsideispresentation
本文由我司收集整编,推荐下载,如有疑问,请与我司联系
onwhichIwillnotdoanycalculation,IgenerallyuseHTML当我在javascript方面需
要的是表示时,我不会做任何计算,我通常使用HTMLThemainadvantageofusing
HTMLiswhenyouwanttoreplaceafullportionofyourpagewithwhatcomesbackfrom
theAjaxrequest:
使用HTML的主要优点是,当您希望用Ajax请求返回的内容替换整个页面时:
Re-buildingaportionofpageinJSis(quite)hard用JS重新构建页面的一部分是
非常困难的Youprobablyalreadyhavesometemplatingengineontheserverside,that
wasusedtogeneratethepageinthefirstplace...Whynotreuseit?
您可能已经在服务器
端有了一些模板引擎,这些引擎最初用于生成页面……为什么不重用它呢?
I
generallydon’treallytakeintoconsiderationthe“performance”sideofthings,atleaston
theserver:
我通常不会考虑事情的“性能”方面,至少在服务器上是这样的:
Ontheserver,generatingaportionofHTMLorsomeJSONwon’tprobablymake
thatmuchofadifference在服务器上,生成一部分HTML或一些JSON可能不会有
太大的差别Aboutthesizeofthestuffthatgoesthroughthenetwork:
well,you
probablydon’tusehundredsofKBofdata/html...Usinggziponwhateveryouare
transferringiswhat’sgoingtomakethebiggestdifference(notchoosingbetweenHTML
andJSON)关于通过网络的东西的大小:
嗯,你可能不会使用几百KB的数据/html…
在传输的任何东西上使用gzip都将产生最大的差异(而不是在HTML和JSON之间
进行选择)Onethingthatcouldbetakenintoconsideration,though,iswhatresources
you’llneedontheclienttorecreatetheHTML(ortheDOMstructure)fromtheJSON
data...comparethattopushingaportionofHTMLintothepage;-)不过,可以考虑的一
点是,客户端需要什么资源来从JSON数据中重新创建HTML(或DOM结构)……将
其与将HTML的一部分放入页面进行比较;-)Finally,onethingthatdefinitlymatters:
最后,有一点非常重要:
HowlongwillittakeyoutodevelopanewsystemthatwillsenddataasJSON+
本文由我司收集整编,推荐下载,如有疑问,请与我司联系
codetheJSrequiredtoinjectitasHTMLintothepage?
开发一个新系统需要多长时间
才能将数据以JSON+代码的形式发送到页面中?
Howlongwillittaketojustreturn
HTML?
Andhowlongifyoucanre-usesomeofyouralreadyexistingserver-sidecode?
返回HTML需要多长时间?
如果您可以重用一些已经存在的服务器端代码,需要多
长时间?
Andtoansweranotheranswer:
ifyouneedtoupdatemorethanoneportionof
thepage,thereisstillthesolution/hackofsendingallthosepartsinsideonebigstringthat
groupsseveralHTMLportions,andextracttherelevantpartsinJS.
为了回答另一个问题:
如果需要更新页面的多个部分,仍然可以将所有这些部分发
送到一个大字符串中,该字符串将多个HTML部分分组,并用JS提取相关部分。
Forinstance,youcouldreturnsomestringthatlookslikethis:
例如,您可以返回如下所示的字符串:
!
--MARKER_BEGIN_PART1--heregoesthehtmlcodeforpart1!
--
MARKER_END_PART1--!
--MARKER_BEGIN_PART2--heregoesthehtmlcode
forpart2!
--MARKER_END_PART2--!
--MARKER_BEGIN_PART3--heregoes
thejsondatathatwillbeusedtobuildpart3fromtheJScode!
--MARKER_END_PART3
--Thatdoesn’tlookreallygood,butit’sdefinitlyuseful(I’veuseditquiteacoupleof
times,mostlywhentheHTMLdataweretoobigtobeencapsulatedintoJSON):
youare
sendingHTMLfortheportionsofthepagethatneedpresentation,andyouaresending
JSONforthesituationyouneeddata...
这看起来不很好,但是在街上有用(我使用了很几次,通常是在HTML数据太大被封
装成JSON):
你发送HTML页面的部分需要演讲,和你发送JSON的情况你需要数
据……
...Andtoextractthose,theJSsubstringmethodwilldothetrick,Isuppose;-)
…要提取这些,我想JS子字符串方法可以起到这个作用;-)
102
Imainlyagreewiththeopinionsstatedhere.Ijustwantedtosummarizethemas:
本文由我司收集整编,推荐下载,如有疑问,请与我司联系
我主要同意这里的观点。
我想总结一下
ItisbadpracticetosendHTMLifyouendupparsingitclient-sidetodosome
calculationsoverit.
如果您最终对HTML进行客户端解析并对其进行一些计算,那么发送HTML是
不好的做法。
ItisbadpracticetosendJSONifallyou’llendupdoingistoincorporateitintothe
page’sDOMtree.
如果您最终要做的只是将JSON合并到页面的DOM树中,那么发送JSON是不
好的做法。
好吧,
I’moneofthoserarepersonsthatlikestoseparatethingsthisway:
-Theserveris
responsiblefordeliveringdata(model);-Theclientisresponsibleforshowing(view)and
manipulatingdata(model);
我是那种喜欢以这种方式分离事物的少数人之一:
服务器负责交付数据(模型);-客
户端负责显示(视图)和操作数据(模型);
So,theservershouldfocusondeliveringthemodel(inthiscaseJSONisbetter).This
wayyougetaflexibleapproach.Ifyouwanttochangetheviewofyoumodel,youkeep
theserversendingthesamedataandjustchangetheclient,javascriptcomponents,that
changethatdataintoaview.Imagine,youhaveaserverdeliveringdatatomobiledevices
aswellasdesktopapps.
因此,服务器应该专注于交付模型(在这种情况下,JSON更好)。
这样你就有了一
个灵活的方法。
如果您想要更改模型的视图,您可以让服务器发送相同的数据,并
仅更改客户机、javascript组件,将数据更改为视图。
想象一下,你有一个服务器将
数据传送到移动设备和桌面应用程序。
Also,thisapproachincreasesproductivity,sincetheserverandclientcodecanbebuilt
atthesametime,neverlosingthefocuswhichiswhathappenswhenyoukeepswitching
本文由我司收集整编,推荐下载,如有疑问,请与我司联系
fromjstoPHP/JAVA/etc.
另外,这种方法提高了生产率,因为服务器和客户端代码可以同时构建,永远不
会失去焦点,这是当您从js切换到PHP/JAVA/等时所发生的事情。
Generally,Ithinkmostpeopleprefertodoasmuchaspossibleontheserverside
becausetheydon’tmasterjs,sotheytrytoavoiditasmuchaspossible.
一般来说,我认为大多数人喜欢在服务器端尽可能多地做,因为他们不精通js,
因此他们尽量避免使用js。
Basically,IhavethesameopinionasthoseguysthatareworkingonAngular.Inmy
opinionthatisthefutureofwebapps.
基本上,我和那些研究角度的人有相同的观点。
在我看来,这就是网络应用的未
来。
9
IhavesomethinginterestingIthoughtImightadd.Idevelopedanapplicationthatonly
everloadedafullviewonetime.Fromthatpointforwarditcommunicatedbacktothe
serverwithajaxonly.Itonlyeverneededtoloadonepage(myreasonforthisis
unimportanthere).TheinterestingpartcomesinthatIhadaspecialneedtoreturnsome
datatobeoperatedoninthejavascriptANDapartialviewtobedisplayed.Icouldhave
splitthisupintotwocallstotwoseparateactionmethodsbutIdecidedtogowith
somethingalittlemorefun.
我有一些有趣的东西,我想我可以添加。
我开发了一个应用程序,它只加载了一
次完整的视图。
从此以后,它只使用ajax与服务器通信。
它只需要加载一个页面(我
的原因在这里不重要)。
有趣的是,我特别需要返回一些要在javascript中操作的数
据和显示的部分视图。
我本可以把它分成两个调用,分别调用两个不同的动作方
法,但我决定用一些更有趣的东西。
Checkitout:
检查一下:
本文由我司收集整编,推荐下载,如有疑问,请与我司联系
publicJsonResultMyJsonObject(stringsomeData)returnJson(new{SomeData=
someData,PartialView=RenderPartialViewToString(“JsonPartialView”,null)},
JsonRequestBehavior.AllowGet);WhatisRenderPartialViewToString()youmightask?
It
isthislittlenuggetofcoolnessrighthere:
您可能会问什么是RenderPartialViewToString()?
这是一个小小的冷元素:
protectedstringRenderPartialViewToString(stringviewName,objectmodel)
ViewData.Model=model;using(StringWritersw=newStringWriter())
ViewEngineResultviewResult=
ViewEngines.Engines.FindPartialView(ControllerContext,viewName);ViewContext
viewContext=newViewContext(ControllerContext,viewResult.View,ViewData,
TempData,sw);viewResult.View.Render(viewContext,sw);return
sw.GetStringBuilder().ToString();Ihaven’tdoneanyperformancetestingonthissoI’m
notsureifitincursanymoreorlessoverheadthancallingoneactionmethodforthe
JsonResultandonefortheParticalViewResult,butIstillthoughtitwasprettycool.Itjust
serializesapartialviewintoastringandsendsitalongwiththeJsonasoneofit’s
parameters.IthenuseJQuerytotakethatparameterandslapitintoit’sappropriateDOM
node:
)
我还没有做过任何性能测试,因此我不确定它是否会比调用JsonResult的一个操
作方法和一个粒子viewresult来产生更多的开销,但是我仍然认为它很酷。
它只是
将部分视图序列化为字符串,并将其连同Json作为参数之一发送出去。
然后,我使
用JQuery将该参数添加到相应的DOM节点中:
)
Letmeknowwhatyouthinkofmyhybrid!
让我知道你对我的混血儿的看法!
8
Iftheresponseneedsnofurtherclient-sideprocessing,HTMLisOKinmyopinion.
SendingJSONwillonlyforceyoutodothatclient-sideprocessing.
本文由我司收集整编,推荐下载,如有疑问,请与我司联系
engineseveryday.Sothespeedofclientparsingisnotanimportantissuerightnow,even
more,JSONobjectsareususallyverysmallsotheydon’tconsumealotofclientside
resourses.Iprefertohaveaslowwebsiteforsomeuserswithslowbrowserratherthan
slowsiteforeveryonebecauseofveryloadedserver.
JSON是非常多功能性和轻量级的格式。
当我开始使用它作为客户端模板解析器
数据时,我发现了它的美妙之处。
让我解释一下,以前我在服务器端使用smarty和
视图(生成高服务器负载),现在我使用一些自定义jquery函数,所有数据都在客户
端呈现,使用客户端浏览器作为模板解析器。
它节省了服务器资源,另一方面浏览
器每天都在改进它们的JS引擎。
因此,客户端解析的速度现在并不是一个重要的问
题,而且JSON对象通常非常小,因此它们不会消耗大量客户端资源。
我更喜欢用
慢的浏览器而不是慢速的网站给每个人,因为每个人都是很有负载的服务器。
Onanotherhand,sendingpuredatafromserveryouabstractitfrompresentationso,if
tomorrowyouwanttochangeitorintegrateyourdataintoanotherserviceyoucandoit
mucheasier.
另一方面,从服务器发送纯数据,您可以从表示中抽象数据,因此,如果明天想
要更改数据或将数据集成到另一个服务中,您可以更容易地完成。
Justmy2cents.
那只是我的个人意见。
6
Ifyouwantacleandecoupledclient,whichinmyopinionisbestpractice,thenitmakes
sense