在动态预览功能中调用PHP函数

时间:2014-07-09 08:30:29

标签: javascript php

我有一个允许用户输入数据的表单,在提交表单之前,它允许他们预览他们的工作:

<form>
...
<textarea id="option-question" name="option-question" cols="65" rows="7"></textarea><br />
<button onclick="preview_mc('question')" type="button">Preview</button><br />
</form>

预览功能如下所示:

function preview_mc(part){
$("#preview-"+part).text($("#option-"+part).val()).html(function(index, old) { return old.replace(/\n/g, '<br />') });
var math = document.getElementById("preview-"+part);
MathJax.Hub.Queue(["Typeset",MathJax.Hub,math]);
}

(每页有多个“部分”)。

当我从数据库调用数据时,它使用解析函数进行基本的bbcode解析,让我们称之为parse_message。如何让预览也通过bbcode消息解析?编写一个模拟解析消息的javascript函数或以某种方式通过js调用PHP函数会更好吗? (如果编写javscript函数是最佳答案,那么非常感谢帮助这样做!)

这是消息解析:

function parse_message($message){
$find = array(
'~\[b\](.*?)\[/b\]~s',
'~\[i\](.*?)\[/i\]~s',
'~\[u\](.*?)\[/u\]~s',
'~\[quote\](.*?)\[/quote\]~s',
'~\[url\]((?:ftp|https?)://.*?)\[/url\]~s',
'~\[img\](https?://.*?\.(?:jpg|jpeg|gif|png|bmp))\[/img\]~s'
);

// HTML tags to replace BBcode
$replace = array(
'<b>$1</b>',
'<i>$1</i>',
'<span style="text-decoration:underline;">$1</span>',
'<blockquote>$1</'.'blockquote>',
'<a href="$1">$1</a>',
'<img src="$1" alt="" />'
);

// Replacing the BBcodes with corresponding HTML tags
return preg_replace($find,$replace,$message);
}

1 个答案:

答案 0 :(得分:0)

感谢Darren的帮助。以下是我最终获得的代码:

使用Javascript:

function preview_mc(part){
    $("#preview-"+part).text($("#option-"+part).val()).html(function(index, old) { return old.replace(/\n/g, '<br />') });
    $.ajax({
        url: 'include/functions.php',
        type: 'post',
        data: { "parse_message_call": $("#preview-"+part).text()},
        success: function(response) { $("#preview-"+part).html(response); var math = document.getElementById("preview-"+part); MathJax.Hub.Queue(["Typeset",MathJax.Hub,math]);}
    }); 
}

PHP:

function parse_message($message){
    $find = array(
    '~\[b\](.*?)\[/b\]~s',
    '~\[i\](.*?)\[/i\]~s',
    '~\[u\](.*?)\[/u\]~s',
    '~\[quote\](.*?)\[/quote\]~s',
    '~\[url\]((?:ftp|https?)://.*?)\[/url\]~s',
    '~\[img\](https?://.*?\.(?:jpg|jpeg|gif|png|bmp))\[/img\]~s'
    );

    // HTML tags to replace BBcode
    $replace = array(
    '<b>$1</b>',
    '<i>$1</i>',
    '<span style="text-decoration:underline;">$1</span>',
    '<blockquote>$1</'.'blockquote>',
    '<a href="$1">$1</a>',
    '<img src="$1" alt="" />'
    );

    // Replacing the BBcodes with corresponding HTML tags
    return preg_replace($find,$replace,$message);
}

// for ajax
if(isset($_POST['parse_message_call'])) {
    echo parse_message($_POST['parse_message_call']);
}
相关问题