我正在制作一个访问者可以订阅邮件列表的表单。
代码是:
function subscribe_form() {
global $my_subme;
$form = '';
$msg = '';
if ( isset( $_GET['status'] ) ) {
if ( 'subscribed' === $_GET['status'] ) {
$msg = __( 'Thank you for confirming your subscription', 'subme' );
} else if ( 'unsubscribed' === $_GET['status'] ) {
$msg = __( 'You have successfully unsubscribed.', 'subme' );
} else {
$msg = __( 'Sorry, but something went wrong.', 'subme' );
}
$form .= '<p>';
$form .= esc_html( $msg );
$form .= '</p>';
} else {
/* Process the form when submitted */
if ( ( isset( $_POST['subscribe'] ) || isset( $_POST['unsubscribe'] ) ) && isset( $_POST['source'] ) && 'widget' === $_POST['source'] ) {
/* Check nonce */
if ( ! isset( $_POST['subme_widget_nonce'] ) || ! wp_verify_nonce( $_POST['subme_widget_nonce'], 'subme_widget' ) ) {
return;
}
if ( ! isset( $_POST['email'] ) ) {
return;
}
if ( ! $my_subme->is_valid_email( strtolower( $_POST['email'] ) ) ) {
$msg = __( 'Sorry, but this does not seem like a valid email address.', 'subme' );
} else {
if ( isset( $_POST['subscribe'] ) ) {
$msg = $my_subme->subscribe( $_POST['email'] );
} else {
$msg = $my_subme->unsubscribe( $_POST['email'] );
}
}
}
$form .= '<form method="post">';
$form .= wp_nonce_field( 'subme_widget', 'subme_widget_nonce', true, false );
$form .= '<input type="hidden" name="source" value="widget" />';
$form .= '<p>';
$form .= __( 'Your email address:', 'subme' ) . '<br />';
$form .= '<input type="text" name="email" /><br /><br />';
$form .= '<input type="submit" name="subscribe" value="' . __( 'Subscribe', 'subme' ) . '" />';
$form .= ' ';
$form .= '<input type="submit" name="unsubscribe" value="' . __( 'Unsubscribe', 'subme' ) . '" />';
$form .= '</p>';
$form .= '</form>';
if ( strlen( $msg ) > 0 ) {
$form .= '<p>';
$form .= esc_html( $msg );
$form .= '</p>';
}
}
echo $form;
echo '</div>';
}
subscribe_form();
如何更改此代码以便使用ajax进行处理?正如您所看到的,当前用户提交表单时,它只是简单的页面刷新。
答案 0 :(得分:0)
如果您有两个提交,则只会将第二个提交给表单...您需要执行类似2个表单的操作,或添加onclick事件以更改名称或类型或隐藏值...像:
<input type="submit" onclick="document.getElementById('action').value='subscribe'" value="Subscribe" />
<input type="submit" onclick="document.getElementById('action').value='unsubscribe'" value="Unsubscribe" />
<input type="hidden" name="action" id="action" />
答案 1 :(得分:0)
1.-你展示的代码是php,好的。这是服务器端。
2.-从客户端。你应该有代码javascript发送到服务器,这个客户想要订阅的数据。