【发布时间】:2020-10-19 11:28:42
【问题描述】:
我正在尝试通过 AJAX 请求发送 following content,我需要将 html 内容存储在数据库列中。
到目前为止,我所做的是尝试在将 html 发送到AJAX 之前对其进行转义:
let escapedHtml = escapeHtml(content); // content contains the html above (pastebin)
let campaign.content = escapedHtml;
let postData = { campaign: JSON.stringify(campaign) };
let postUrl = 'some url';
$.post(postUrl, postData, function (response) {
console.log('Yeah, we did it!');
}, 'json').fail(function(){
console.log('Something bad happened');
});
我已经为转义定义了一个自定义函数:
function escapeHtml(string) {
var entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
return String(string).replace(/[&<>"'`=\/]/g, function (s) {
return entityMap[s];
});
}
AJAX 请求将内容发送到Codeigniter 控制器,我按以下方式处理:
public function ajax_save_campaign()
{
try
{
$campaign = json_decode($this->input->post('campaign'), TRUE);
$this->load->model('newsletter_model');
$campaignId = $this->newsletter_model->add_campaign($campaign);
$this->output
->set_content_type('application/json')
->set_output(json_encode([
'status' => AJAX_SUCCESS,
'id' => $campaignId
]));
}
catch(Exception $exc)
{
$this->output
->set_content_type('application/json')
->set_output(json_encode([
'exceptions' => [exceptionToJavascript($exc)]
]));
}
}
问题在于,如果我转储变量 $campaign['content'],我不会得到正确的 html,但 this 这是完全不同的。那么AJAX请求完成后如何从php中恢复原来的html结构呢?
谢谢。
更新
我无法发送原始 html,因为这会破坏包含其他属性的 $campaign 变量,例如(html 没有像上面的 escapeHtml 那样转义):
$campaign = json_decode($this->input->post('campaign'), TRUE);
var_dump($campaign);
变量$campaign实际上是NULL
这个$this->input->post('campaign') 包含以下内容:
"{"campaign_name":"hello world","sender_title":"test","reply_email":"hello@uxdes54.com","subject":"test","launch_date":1593426034,"groups":"1","templates":"1","content":"<p>Lethe Newsletter Verification</p>\n\n<p> </p>\n\n<p><!-- page content --></p>\n\n<div id=\ xss=removed>\n<h3>{ORGANIZATION_NAME}<br>\n<small>E-Mail Verification</small></h3>\n\n<hr>\n<p>Hello {SUBSCRIBER_NAME},</p>\n\n<p>Welcome to {ORGANIZATION_NAME}! Please take a second to confirm <span xss=removed>{SUBSCRIBER_MAIL}</span> as your email address by clicking this link:</p>\n\n<p><strong>{VERIFY_LINK[Click Here!]}</strong></p>\n\n<p>Once you do, you will be able to opt-in to notifications of activity and access other features that require a valid email address.</p>\n\n<p>Thank You!</p>\n\n<hr>\n<div xss=removed><small>{company_name}<br>\n{company_phone_1} - {company_phone_2} </small></div>\n</div>\n\n<div id=\ xss=removed><small>{LETHE_SAVE_TREE}</small></div>\n\n<p><!-- page content --></p>\n\n<p> </p>\n"}"
【问题讨论】:
-
如果您只是将 HTML 从 JS 发送到 PHP 以存储在数据库中,则无需转义 HTML。您需要做的唯一转义是 SQL 注入,但 CI 的 db-class 已经为您处理了。只需“按原样”发送和存储即可。如果您稍后想要将 HTML 输出为代码,而不让浏览器将其呈现为 HTML,那么您需要对 HTML 进行转义。
-
@MagnusEriksson 如果我不转义内容,则变量
$campaign已完全损坏,因此我无法访问该变量的其他属性 -
我删除了关于 JSON 的评论,因为我错过了它是您传递的对象而不仅仅是内容。但是html仍然不需要转义。如果您失败了,那么您应该让我们知道会发生什么。
-
@MagnusEriksson 请检查我的更新
标签: javascript php jquery ajax codeigniter