How to display a JSON response on separate lines using jQuery and PHP

后端 未结 4 916
离开以前
离开以前 2021-01-16 07:54

I am using AJAX to submit a form, and would like to display a summary of the information on the page so that the user can confirm the information before submitting. I am hav

相关标签:
4条回答
  • 2021-01-16 08:00

    You need to insert <br /> tags or insert \n and then put the content in pre tag. Remeber you are injecting this content into an html DOM so html rules still apply :-)

    0 讨论(0)
  • 2021-01-16 08:02
    $return['message'] = 'First Entry: ' . $_POST['Name1'] . '<br />'  . 'Second Entry: ' .    $_POST['Name2'] . '<br />' . 'Third Entry: ' . $_POST['Name3'];
    
    0 讨论(0)
  • 2021-01-16 08:22

    Generally you want to use json_encode on arrays. So your PHP array would look like:

    $arr = array('foo' => 1, 'bar' => 2, 'baz' => 'test');
    // you can probably just use $_POST here, i.e. $arr = $_POST
    
    echo json_encode($arr);
    

    And your JavaScript dealing with that data variable would look like this:

    $('#id').html(data.foo + "<br />" + data.bar + "<br />" + data.baz);
    

    This lets you deal with your data piecewise, rather than in one lump, so it's easier to manipulate and parse.

    0 讨论(0)
  • 2021-01-16 08:23

    You can transfer JSON encoded HTML newlines like this:

    $return['message'] = 'First Entry: ' . $_POST['Name1'] . '<br /> '  . 'Second Entry: ' .    $_POST['Name2'] . '<br /> ' . 'Third Entry: ' . $_POST['Name3'];  
    echo json_encode($return);
    

    Or convert newlines (\n) into newline tags.

    The nicer way though would be to leave that kind of processing to the client by e.g. returning an array of messages:

    $return['message'] = array();
    $return['message'][] = 'First Entry: ' . $_POST['Name1'];
    $return['message'][] = 'Second Entry: ' . $_POST['Name2'];
    $return['message'][] = 'Third Entry: ' . $_POST['Name3'];
    echo json_encode($return);
    

    And leave the processing to the client (maybe the client wants the messages wrapped in a paragraph tag later on):

    function(data)
    {
        $('<div id="output2"></div>').insertAfter($('#agreement-information'));
        $('#output2').html(data.message.join('<br />')).show(500);
        $('#ouput2').append(data);  
    }
    
    0 讨论(0)
提交回复
热议问题