doudian6229 2012-04-17 09:27
浏览 39
已采纳

Javascript评估HTML特殊字符,打破AJAX结果中的函数调用

I've been working on a custom form completion for a site/tool I've been building.

I got the search to work, it displays the results in a little div below the input field. I want to allow a user to see the results, click on the appropriate result, and allow it to populate the form fields with the corresponding data. This works when the data has no special characters in it (IE an apostrophe), but if it has an apostrophe, the function call breaks. I know well enough to have the special characters changed into HTML special characters:

'

And, I have done that when adding the data to the database. The problem is, since the function call is placed via AJAX into a div, the HTML special character is "evaluated" when placed into the page, and becomes the literal character. Here is an example of the function call:

onclick="popForm('1234', 'Some Name', 'Another Name', 'Someguy's Thing', '5678')"

Here's a list of all that I'm trying to do:

  1. User enters data into a field
  2. A javascript function captures the input via onkeyup(), and processes it
  3. The function uses AJAX to make a call to a PHP script
  4. The PHP script performs the search, grabs the results, and echo's a table containing the results, as well as a function call for onclick to populate the fields.
  5. Javascript handles the results from AJAX, and adds the results to a div's innerhtml.
  6. User clicks on a result, onclick is triggered, makes function call with string arguments wrapped in single quotes
  7. Function adds the strings to the appropriate fields via document.getElementById("fieldname").value=string;
  8. User submits form

Currently, we get all the way up to step 6, which is where it breaks, due to the literal apostrophe in the function call.

Any ideas on how to remedy this?

  • 写回答

3条回答 默认 最新

  • dr9379 2012-04-17 10:06
    关注

    I would seriously consider re-writing your logic.

    1. don't use inline DOM0 event handlers - they're error prone for exactly this sort of reason
    2. Return data, not function calls - eval is bad, mkay?
    3. Bind a proper event handler (ideally using element.addEventListener) to a first-class function created on the fly and attached to the appropriate element
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向