我正在尝试通过 AJAX 请求发送以下内容,我需要将 html 内容存储在数据库列中。
到目前为止,我所做的是在将其发送到AJAX
之前尝试转义 html:
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,但这完全不同。那么当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>nn<p> </p>nn<p><!-- page content --></p>nn<div id= xss=removed>n<h3>{ORGANIZATION_NAME}<br>n<small>E-Mail Verification</small></h3>nn<hr>n<p>Hello {SUBSCRIBER_NAME},</p>nn<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>nn<p><strong>{VERIFY_LINK[Click Here!]}</strong></p>nn<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>nn<p>Thank You!</p>nn<hr>n<div xss=removed><small>{company_name}<br>n{company_phone_1} - {company_phone_2} </small></div>n</div>nn<div id= xss=removed><small>{LETHE_SAVE_TREE}</small></div>nn<p><!-- page content --></p>nn<p> </p>n"}"
正如Magnus Eriksson在评论中所说,你应该通过ajax将原始HTML代码发送到PHP控制器,并将其插入到数据库中。
通过转储获得的内容正是您要获取的内容 - 转义字符串。在你的PHP中,没有函数(至少我看不到它(可以取消转义你在JS端逃脱的内容。
通过 ajax 发送完整的 HTML 字符串应该不会有任何问题。
编辑:为什么你把数据作为JSON而不是对象本身发送?
$.ajax({
type: 'POST',
url: post_url,
data: {
campaign: campaign
},
success: function(msg) {
console.log(msg)
}
});