jQuery AJAX post 只查找多行文本框的第一行

jQuery AJAX post only finds first line of mult line textbox

我在 WordPress 上有一个 POST 表单,我用它通过 API.

将数据传递给 MailChimp

就其本身而言(即不使用 jQuery),它按预期工作。但是,当我尝试通过 AJAX post 操作而不是使用表单的操作导航到新页面时,它只找到多行文本框的第一行。

表格

<?php 

    // Template Name: MailChimp Form 
    get_header();

?>

<form id="mailchimp_actions" method="post" action="/ajax-curl-actions/">
    <select name="action" id="action">
        <option>Subscribe</option>
        <option>Unsubscribe</option>
        <option>Find</option>
    </select>
    <textarea name="import_data" id="import_data" placeholder="Email Address,First Name,Last Name"></textarea>
    <input type="submit">
</form>

<?php get_footer(); ?>

处理 $_POST 数据的页面

<?php 

    // Template: AJAX - cURL actions.

    ###############################################################################
    #                                                                             # 
    #   Available options:                                                        #
    #                                                                             #     
    #   Add New Subscriber - Create a new subscriber and add them to a list.      #
    #   Subscribe - Add an existing email to the specified list.                  #
    #   Unsubscribe - Completely unsubscribe an email from all mailers.           #
    #   Update - Change subscriber information.                                   #
    #                                                                             #
    ###############################################################################

    $subscribers = bfm_data_format($_POST);

    $final_report = array('successes'=>0,'failures'=>array());

    foreach($subscribers as $subscriber) :
        $post_data = array('email' => $subscriber[0], 'fname' =>  $subscriber[1], 'lname' =>  $subscriber[2]);
        $action = $_POST['action'];
        if(!bfm_subscriber_exists($subscriber[0]) && $action=='Subscribe') $action = 'Add New Subscriber';
        $report = bfm_curl_actions(bfm_list_id(),bfm_api_key(),$post_data,$action);     
        if($report['success']) :
            $final_report['successes']++;   
        else:
            $final_report['failures'][] = $report['error'];
        endif;
    endforeach;

?>

函数

// Format data

    function bfm_data_format($data) {
        $import_data = $data['import_data'];
        $import_data_lines = explode("\n",$import_data);
        $i=0;
        foreach($import_data_lines as $import_data_line) :
            $import_data_lines[$i] = explode(',',$import_data_line);
            $i++;
        endforeach;
        return $import_data_lines;
    }

    // MailChimp data manipulation  

    function bfm_curl_actions($list_id,$api_key,$post_data,$action) {

        $auth = base64_encode( 'user:'.$api_key );

        $data = array(
            'apikey'        => $api_key,
            'email_address' => $post_data['email'],
            'merge_fields'  => array(
            'FNAME' => $post_data['fname'],
            'LNAME' => $post_data['lname'],
            )
        );

        if($action == 'Subscribe' || $action == 'Add New Subscriber') :
            $data['status']='subscribed';
        elseif($action == 'Unsubscribe'):
            $data['status']='unsubscribed';
        endif;

        $member_id = md5($post_data['email']);

        $json_data = json_encode($data);

        $ch = curl_init();

        $curlopt_url = "https://us7.api.mailchimp.com/3.0/lists/$list_id/members/";
        if($action!='Add New Subscriber') $curlopt_url.=$member_id; // Member ID needs to be excluded if adding an entirely new person.
        curl_setopt($ch, CURLOPT_URL, $curlopt_url);
        if($action == 'Subscribe' || $action == 'Unsubscribe' || $action == 'Update') : 
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
        endif;
        if($action == 'Find'):
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        endif;
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
            'Authorization: Basic '.$auth));
        curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);

        $result = curl_exec($ch);
        $status = "undefined";
        $msg = "";
        $myArray = json_decode($result, true);

        foreach($myArray as $key => $value)
        {

            if( $key == "status" )
            {
                $status=$value;             
            }
            else if ($key == "title")
            {
                $msg=$value;                
            }       

        }

        $email = $post_data['email'];

        if($action == 'Subscribe' || $action == 'Add New Subscriber'): 
            if($status == "subscribed") :
                $report = array ('success'=>true,'error'=>'');
            else: 
                $report = array('success'=>false,'error'=>array('email'=>$email,'message'=>$msg));
            endif;          
        endif;

        return $report;     

    }


    function bfm_subscriber_exists($email) {

        $api_key = bfm_api_key();
        $list_id = bfm_list_id();

        $auth = base64_encode( 'user:'.$api_key );

        $data = array(
            'apikey'        => $api_key,
            'email_address' => $email,
        );

        $member_id = md5($email);

        $json_data = json_encode($data);

        $ch = curl_init();

        $curlopt_url = "https://us7.api.mailchimp.com/3.0/lists/$list_id/members/$member_id";

        curl_setopt($ch, CURLOPT_URL, $curlopt_url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
            'Authorization: Basic '.$auth));
        curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);

        $result = json_decode(curl_exec($ch),true);

        if ($result['status']=='404') return false;

        return true;

        die(' '); // Free up memory.

    }

按原样,这按预期工作。第二页将第一页的数据导入 MailChimp。

但是,如果我尝试使用以下 jQuery 通过 AJAX 执行相同操作,它仍会导入 MailChimp,但仅包含多行文本框的第一行;所有其他行都将被忽略。

$(document).on("submit","#mailchimp_actions", 
        function(event) {
            event.preventDefault();
            var bfm_action = $('#action').val();
            var bfm_import = encodeURIComponent($('#import_data').val());
            console.log(bfm_action);
            console.log(bfm_import);
            $.post("/ajax-curl-actions/",
                {   
                    import_data: bfm_import,
                    action: bfm_action,
                },
                function () {
                    alert("Successful import.");    
                }
            );  
        }
    );

我错过了什么?我如何让它识别文本框中的所有行?

请尝试更改这行代码

function bfm_data_format($data) {
  $import_data = nl2br(urldecode($data['import_data']));
  $import_data_lines = explode("\n", $import_data);
  $i = 0;
  foreach ($import_data_lines as $import_data_line) :
      $import_data_lines[$i] = explode(',', $import_data_line);
      $i++;
  endforeach;
  return $import_data_lines;
}

问题似乎是由双重转义变量引起的:当您将键值对作为对象发送时,一次由您转义,然后 jQuery 再次转义一次。

如果您将键值对发送到 jQuery 的任何 ajax 方法,jQuery 会为您处理转义,因此您可以删除 encodeURIComponent :

$(document).on("submit","#mailchimp_actions", 
    function(event) {
        event.preventDefault();
        var bfm_action = $('#action').val();
        var bfm_import = $('#import_data').val();
                         ^^^^^^^^^^^^^^^^^^^^^^^ here
        console.log(bfm_action);
        console.log(bfm_import);
        ...