在JavaScript的Ajax响应 [英] JavaScript in AJAX Response

查看:71
本文介绍了在JavaScript的Ajax响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有关于AJAX一个一般性的问题。是不是还好在AJAX响应发送JavaScript和执行呢?或者是唯一优雅的方式来无论是使用JSON或纯HTML的响应? 我的问题是,我正在寻找处理这些导致HTML的插入或JavaScript的执行,取决于用户数据的AJAX请求的最佳方式。

I've got a general question about AJAX. Is it okay to send JavaScript in an AJAX response and execute it? Or is the only elegant way to respond either with JSON or plain HTML? My problem is that I am searching for the best way to handle AJAX requests which are leading to the insertion of HTML OR the execution of JavaScript, depending on user data.

多谢了。

推荐答案

我会认为,这将Ajax响应后执行JavaScript函数是标准的为大家除了一些变量。如果是这样的话,你应该包括被正常加载,在你的脚本文件中的JavaScript函数。然后有Ajax响应回来与你所需要的,喜欢的用户ID的变量。然后使用该变量调用每次注入了新的功能的JavaScript函数,而不是正常。

I would think that the JavaScript function that would be executed after the AJAX response would be standard for everyone aside from some variable. If that is the case, you should include the JavaScript function in your scripts file that gets loaded normally in the . Then have the AJAX response come back with the variable that you need, like the user ID. Then use that variable to call the JavaScript function normally instead of injecting a new function each time.

如果HTML被返回,你可以直接将其插入一个成功的Ajax请求的DOM。

If HTML is returned you can insert it directly into the DOM on a successful AJAX request.

我觉得要走的路将是始终返回JSON,即使它是一个HTML的响应。 JSON响应可能是这样的:

I think the way to go would be to always return JSON even if it's an HTML response. The JSON response could be something like:

{responseType:HTML,VARID:空,有效载荷:< D​​IV>一些HTML< / DIV>中}

如果响应的类型为JS那么VARID可能有变量和有效载荷可以为空。这只是一个例子,但你可以做类似规范的响应,但处理这两种情况下的东西。

If the response were type JS then the varID could have that variable and the payload could be null. That's just an example but you could do something similar to standardize the response but handle both scenarios.

这篇关于在JavaScript的Ajax响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆