파이썬 flask 작은 쇼핑몰, 페이지변경이 안 됨.

조회수 724회

작은 쇼핑몰을 만들려고 노력하는 파이썬 초보입니다. 구조는 메인페이지->상세페이지->결제창 입니다.

메인페이지에서 상품1, 상품2, 상품3, 상품4를 누르면 상세페이지에서 상품코드/가격/배송방법을 db에서 가져와서 뿌리는 형식으로 만들고 있습니다.

이렇게 코드를 짰는데, 메인페이지에서 상품1을 누르던, 상품2를 누르던, 상품3을 누르던 상품 1 페이지만 계속 나오더군요. 다만 콘솔창에서 보면 데이터는 받아오는거 같은데 왜 이럴까요.

$(document).ready(function () {
    console.log(123123)
    product = window.location.href
    product_link = product.split('=')
    console.log(product.split('='))
    console.log(window.location.href)
    detail_page(product_link[1])
})

function detail_page(product_id) {
    console.log(123)
    $.ajax({
        type: "GET",
        url: "/detail?product=" + product_id,
        data: {},
        success: function (response) {
            console.log(response);
            let product_info = response['product_info'];
            make_card(product_info['price'], product_info['code'], product_info['supply'], product_info['delivery'], product_info['tprice'])

        }
    })
}

function make_card(price, code, supply, coupon, delivery, tprice) {
    let temp_html = ' <tbody>\
            <tr>\
                <th>판매가</th>\
                <td class="price">' + price + '</td>\
            </tr>\
            <tr>\
                <th>상품코드</th>\
                <td class="code">'+ code + '</td>\
            </tr>\
            <tr>\
                <th>제조사/공급사</th>\
                <td>' + supply + '</td>\
            </tr>\
            <tr>\
                <th>구매수량</th>\
                <td>\
                    <div class="length">\
                        <input id="count" type="number" min="1" value="1">\
                            <a href="#a">증가</a>\
                            <a href="#a">감소</a>\
                </div>\
            </td>\
        </tr>\
                <tr>\
                    <th>사용가능쿠폰</th>\
                    <td>' + coupon + '</td>\
                </tr>\
                <tr>\
                    <th>옵션선택</th>\
                    <td>\
                        <select id="size">\
                            <option selected value>사이즈를 선택하세요(+0)</option>\
                            <option value="1">85</option>\
                            <option value="2">90</option>\
                            <option value="3">95</option>\
                            <option value="4">100</option>\
                            <option value="5">105</option>\
                            <option value="6">110</option>\
                            <option value="7">115</option>\
                            <option value="8">120</option>\
                            <option value="9">125</option>\
                        </select>\
                    </td>\
                </tr>\
                <tr>\
                    <th>배송비</th>\
                    <td>' + delivery + '</td>\
                </tr>\
                <tr>\
                    <th>결제금액</th>\
                    <td class="tprice"><b>'+ tprice + '</b>원</td>\
                </tr>\
    </tbody>\
</table>'
}

<body>

    <div class="product_view">
        <h2>SK대리점 하계 유니폼 상의</h2>
        <table>
            <caption>
                <details class="hide">
                    <summary>상품정보</summary>
                    판매가, 상품코드, 옵션 및 결제금액 안내
                </details>
            </caption>
            <colgroup>
                <col style="width:173px;">
                <col>
            </colgroup>
            <tbody>
                <tr>
                    <th>판매가</th>
                    <td class="price">45,900</td>
                </tr>
                <tr>
                    <th>상품코드</th>
                    <td class="code">C004843</td>
                </tr>
                <tr>
                    <th>제조사/공급사</th>
                    <td class="supply">코오롱 / SK행복나래</td>
                </tr>
                <tr>
                    <th>구매수량</th>
                    <td>
                        <div class="length">
                            <input id="count" type="number" min="1" value="1">
                            <a href="#a">증가</a>
                            <a href="#a">감소</a>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th>사용가능쿠폰</th>
                    <td class="coupon">0개</td>
                </tr>
                <tr>
                    <th>옵션선택</th>
                    <td>
                        <select id="size">
                            <option selected value>사이즈를 선택하세요(+0)</option>
                            <option value="1">85</option>
                            <option value="2">90</option>
                            <option value="3">95</option>
                            <option value="4">100</option>
                            <option value="5">105</option>
                            <option value="6">110</option>
                            <option value="7">115</option>
                            <option value="8">120</option>
                            <option value="9">125</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th>배송비</th>
                    <td class="delivery">무료배송</td>
                </tr>
                <tr>
                    <th>결제금액</th>
                    <td class="tprice"><b>45,900</b>원</td>
                </tr>
            </tbody>
        </table>
        <div class="img">
            <img src="{{url_for('static', filename='image/유니폼 1.jfif')}}" alt="">
            <ul>
                <li class="on"><a href="#a"><img src="{{url_for('static', filename='image/유니폼 1.jfif')}}" alt=""></a>
                </li>
                <li><a href="#a"><img src="{{url_for('static', filename='image/유니폼2.jpg')}}" alt=""></a></li>
            </ul>
        </div>
        <div class="btns">
            <a href="#a" class="btn1">장바구니</a>
            <a href="#a" class="btn2">구매하기</a>
        </div>
    </div>

</body>

</html>
서버
@app.route('/')
def home():
    return render_template('main.html')

@app.route('/product_detail', methods=['GET'])
def change_page():
    product_id = request.args.get('product')
    return render_template("22page.html", product_id=product_id)

@app.route('/detail', methods=['GET'])
def get_detail_product():
    product_id = request.args.get('product')
    print(product_id)
    product_info = db.project.find_one({'name':product_id},{'_id':0})
    print(product_info)

    return jsonify({'result': 'success', 'msg': '상세페이지에 접근하였습니다..', 'product_info':product_info})

if __name__ == '__main__':
    app.run('127.0.0.1', port=5000, debug=True)
  • 이전 질문에 달아드린 답변은 확인해보셨나요? 편집요청빌런 2020.4.27 10:42
  • 확인했는데, 어느 부분을 손봐야할지 감이 안잡혀서 전체 코드를 다시 가져와 봤습니다...ㅠㅠ 알 수 없는 사용자 2020.4.27 10:53
  • 브라우저 개발자 도구 열어서 네트워크 탭을 확인해보세요. product_id를 상품마다 다르게 던지고 있나요? 만약 클릭한 상품은 다른데 서버로 요청하는 product_id가 변하지 않는다면 상품 클릭과 관련된 스크립트와 HTML을 올려보세요. 지금 작성한 내용에는 클릭 이후의 코드만 있으니까요. 편집요청빌런 2020.4.27 10:59
  • 개발자 도구를 열어서 확인해보면, product_detail?product=product1 / product_detail?product=product2 / product_detail?product=product3 / product_detail?product=product4 처럼 각기 다른 코드들을 가지고 오고 있습니다. html 코드도 올려볼게요. 알 수 없는 사용자 2020.4.27 11:02
  • make_card() 함수는 저 내용이 정말 끝인가요? temp_html 변수 생성 후에 아무것도 안하는데요. 편집요청빌런 2020.4.27 11:10
  • 아....혹시 append 함수가 들어가야 될까요? 알 수 없는 사용자 2020.4.27 11:13

1 답변

  • 수수께끼가 풀렸군요 😎:

    function make_card(price, code, supply, coupon, delivery, tprice) {
        let temp_html = '<SOME_MARKUP></SOME_MARKUP>'
    }
    

    변수만 생성하고 아무것도 안하니 변하는게 없는겁니다. 생성한 변수로 태그를 교체하세요.

    jQuery를 쓰고 있으니까 .replaceAll(), .replaceWith(), .html() 중에 마음에 드는거 골라서 쓰시면 됩니다.

    예시:

    let temp_html = '<SOME_MARKUP></SOME_MARKUP>'
    $('#REPLACE_TARGET_TAG').html(temp_html);
    
    • 혹시 td태그 대신에 div태그를 추가하고 타켓태그를 달아야 할까요? 여전히 변화가 없네요 알 수 없는 사용자 2020.4.27 11:42
    • 어디에 추가한다는 말인가요? 예시로 작성한 $('#REPLACE_TARGET_TAG').html(temp_html) 코드는, 'REPLACE_TARGET_TAG'가 ID인 태그를 선택해서 그 하위의 HTML을 모두 temp_html의 내용으로 덮어쓴다는 의미입니다. 스크립트와 마크업에서 ID는 제대로 작성하셨나요? 만약 화면 상의 변화가 단 하나도 없다면 jQuery 셀렉터를 잘못 사용하고 있을 공산이 큽니다. 콘솔에 셀렉터만 호출해봐서 length가 0은 아닌지 확인해보세요. 편집요청빌런 2020.4.27 12:50
    • 아 id를 설정 안했더니 그랬네요...너무 초보라 헤맸습니다. 덕분에 수정 되었습니다. 정말 감사합니다!!  알 수 없는 사용자 2020.4.27 13:45

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)